Radical_Activity Radical_Activity - 3 months ago 8x
PHP Question

How to return multiple relationships with Laravel Eloquent?

I have a table called

. Each of these users has different things:

  • country

  • device

  • computer

  • category

I have created a table for each of these above 'things'. Similar the following:

1 | United States
2 | United Kingdom
3 | Australia
4 | Canada
5 | Italy


I'm storing these values in the users table as follows:

ID | Country | Device | Computer | Category |
1 | 3 | 2 | 6 | 2 |
2 | 4 | 3 | 9 | 1 |


Now each of the above numbers are associated with the corresponding table's ID.

What I want is do an Eloquent Query and search for all the
and 'replacing' their corresponding values from their helper table.

I was thinking about doing a
Eloquent relationship for each of those things in the
table, but then I'm not sure how to get/call them at once.

Anyone can help me tacke this issue?

$model = Model::with('relatedModel', 'relatedModelTwo')->get();

So in your case, it can be something like this. If you only want one relations returned with the user, remove the others.

$user = User::with('country', 'Device', 'Computer', 'Category')->get();

When you dd($user), you should see the related models in the relations array attribute.

To access the relations' properties from there, it is simply


Edit For Comment:

Eloquent will assume the foreign key uses the Model name. So if your user table has the id column, it assumes there will be a column on device table called user_id. If you did this, then you are set and nothing should have to be done.

If you named your column to relate the models something else, you will need to pass that through as a second argument in the relation method.

public function device()
    return $this->hasOne('App\Device', 'foreign_key_here',);

Inversely, if you wanted to get the user the device belongs to, Eloquent will attempt to match the user_id column on the device table to the id column on the user table. As before, if you used a different column to related them, declare the foreign key as the second argument.

public function user()
    return $this->belongsTo('App\User', 'foreign_key_here',);

Laravel Doc One-To-One Relation