I'm a beginner in Laravel and currently trying to create a ticketing system. My tickets
table has two columns which both reference id
from the users
table namely user_id
and handled_by
. I am trying to eager load the full_name
of handled_by
but it is throwing an error "Trying to get property 'full_name' of non-object". I would like to know how to properly create an eloquent relationship between handled_by
and tickets
so I could display the handled_by
's full_name
. Below are snippets of my code.
User Model:
public function tickets(){
return $this->hasMany('\App\Ticket');
}
public function handledBy(){
return $this->hasMany('\App\User', 'handled_by', 'id');
}
Ticket Model:
public function user(){
return $this->belongsTo('\App\User');
}
public function handledBy(){
return $this->belongsTo('\App\User', 'handled_by', 'id');
}
View:
@foreach($tickets as $ticket)
<td class="align-middle text-center">{{ $ticket->handled_by->full_name}}</td>
@endforeach
Controller:
$tickets = Ticket::all()->where('status_id', '1');
return view('admin.open_tickets', compact('tickets'));
In your User model, change \App\User
to \App\Ticket
, and change the method name from handlerBy
to handlers
:
public function handlers(){
return $this->hasMany('\App\Ticket', 'handled_by', 'id');
}
And call it by method's name instead of underline case name:
{{ $ticket->handledBy->full_name}}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments