Laravel: returning results from multiple related tables using eloquent

eloquent, laravel, laravel-4, php

Solution

I just worked through this and learned quite a few things myself. What I did was setup a many to many relationship between `users` and `clients` and created a pivot table for handling the relationship called `tasks` which also stores the description for each task.

It was too much to type here, but you can check out my code at http://paste.laravel.com/Fpv

Problem

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 :)

Original source