Mark
Mark

Reputation: 25

Laravel - leftJoin and reference to elements

I have the following tables in my db:

connections
id
owner_id

owners
id
first_name

ConnectionsController.php

$connections = DB::table('connections')
            ->leftJoin('owners', 'owners.id', '=', 'connections.owner_id')
            ->get();

return view('connections.index', ['connections' => $connections]);

How I can refer in forearch loop to owners.first_name? I have something like this in my connections/index.blade.php

@foreach($connections as $element)
    {{ $element->owners->first_name }}
@endforeach

But it results in "Undefined property". What should I put in my foreach loop to get owners.first_name?

Upvotes: 2

Views: 269

Answers (2)

DevK
DevK

Reputation: 9962

Joins "join" both tables into a single row. You're referencing ->owners object which doesn't exists since properties of both owners and connections are joined into a single row.

This should work:

@foreach($connections as $element)
    {{ $element->first_name }}
@endforeach

But you should also see Alexey Mezenin solution which is the idiomatic Laravel way of doing this and will make your life easier in the long run.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163938

You could use Eloquent. Define a relationship in Connection model:

public function owner()
{
    return $this->belongsTo(Owner::class);
}

Load connections with owners:

$connections = Connection::with('owner')->get();

Display the data:

@foreach($connections as $element)
    {{ $element->owner->first_name }}
@endforeach

If not all connections have an owner, do this:

@foreach($connections as $element)
    {{ optional($element->owner)->first_name }}
@endforeach

Or:

@foreach($connections as $element)
    {{ $element->owner ? $element->owner->first_name : 'There is no owner' }}
@endforeach

Upvotes: 2

Related Questions