Simple Eloquent Relationship

Published 2 years ago by jim1506

I am a newcomer to Laravel which I like, but I find some of the documentation a bit sketchy and I have run into a problem. I am sure it is just me and someone will hopefully will point me in the right direction.

I have a table users and a table countries. Users has a field country_id and both are indexed by id. I have a model User with the following: public function country() { return $this->belongsTo('App\Country'); }

and a model Country with the following (the table has a fields country, abbreviation and flag): public function user() { return $this->hasMany('App/User'); } What I want to do is to call all the users with the attendant info for countries so I can put them into a table. I know this is basic but I admit confusion!

RomainLanz

Hey @jim1506 !

Correct me if I didn't correctly understand your question but you want to get all the users with country information on it?

If yes, it's the perfect job to use Eager Loading.

$users = User::with('country')->get();

Pro Tip: Your user relation on Country model should be called users because it's a HasMany.

jim1506

Thanks. Getting one stage further. In my appropriate view I have the line:

{{ $user->country }}

but it shows up as: {"id":250,"country":"Bangladesh","abbreviation":"BD","flag":"worldflags/Bangladesh.PNG","updated_at":null,"created_at":null}

I pass $users to the view and then have @foreach ($users as $user)

RomainLanz

That's because you are showing the Country object of the user.

If you want to display the name of the country you should get the correct attribute of Country object (seems to be country in your example).

{{ $user->country->country }} 
jim1506

Thanks. I think at last I am getting it!

Please sign in or create an account to participate in this conversation.