I'm using Laravel 4 and in particular I'm looking for an answer that uses eloquent ORM.
I have a table "tasks" which containers a client_id and a user_id assigned to each row.
client_id refers to a client on a "clients" table and user_id refers to a user on a "users" table.
What I want to do: show all tasks and display the "clients" name and "users" first_name
So the result would look like this in my (blade) view:
@foreach($tasks as $task)
<tr>
<td>{{ $task->user->first_name }}</td>
<td>{{ $task->client->name }}</td>
<td>{{ $task->description }}</td>
</tr>
@endforeach
The above view spits out the $task->client->name perfectly fine but unfortunately shows a "Trying to get property of non-object" when I add the line $task->user->first_name
My controller looks like this:
$tasks = Task::with(array('user', 'client'))->get();
return View::make('index', compact('tasks'));
As I understand it my models make a difference too, so my models look like this:
class Task extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function client() {
return $this->belongsTo('Client');
}
public function user() {
return $this->belongsTo('User');
}
}
And:
class User extends Eloquent implements UserInterface, RemindableInterface {
public function task()
{
return $this->hasMany('Task');
}
}
And:
class Client extends Eloquent {
public function projects(){
return $this->hasMany('Project', 'client_id');
}
}
Any ideas on how to make this work? I've been scratching my head for a while - also note I'm not a database relationship pro so the simpler the explanation the better :)