mardi 12 janvier 2016

Laravel 5.1 - Relationships on model with null values

I'm having problem with Relationships on model with null values on Laravel 5.1.

I Have 2 Tables Tasks and Users. In Tasks i have the column id_requester and id_responsible.

I want to show all tasks, i always have a requester, but some times i don't have a responsible yet.

So the id_responsible is null in this cases.

My Model is:

 protected $table = 'tasks';

 protected $fillable = array(
            'id_requester',
            'id_responsible',
        );

public function requester()
    {
        return $this->hasOne('app\User', 'id', 'id_requester');
    }

public function responsible()
    {
        return $this->hasOne('app\User', 'id', 'id_responsible');
    }

The query in my controller is:

$tasks = Tasks::get();

I'm try to show in view like this:

<table>
...
@foreach($tasks as $task)
   <td>{{ $task->requester->name }}</td>

   <td>{{ $task->responsible->name }}</td>
@endforeach
...
</table>

The problem is that when i try access the page I get an error 'Trying to get property of non-object'.

I already test and this is only when i have a id_responsible = Null.

How can i fix this to show all registers?

Thanks!!!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire