How to use column from other table in laravel?

Member

by deron , in category: PHP Frameworks , 5 months ago

How to use column from other table in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 5 months ago

@deron 

To use a column from another table in Laravel, you can make use of Eloquent relationships. Here is an example of how to retrieve a column from another table in Laravel:

  1. Define a relationship between the two models:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// User model
class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}

// Profile model
class Profile extends Model
{
    protected $fillable = ['user_id', 'bio'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}


  1. Access the column from the other table:
1
2
$user = User::find(1);
$bio = $user->profile->bio;


In this example, we have defined a one-to-one relationship between the User and Profile models. The User model has a profile() method that defines the relationship, and the Profile model has a user() method that defines the inverse relationship.


You can then access the bio column from the Profile table by accessing the profile property on the User model instance.


Note that you should make sure that there is a valid relationship between the two tables in your database schema. If the foreign key constraint is missing, the relationship will not work properly.