I have noticed that the index method of my resource controller returns all of the relationships that I request in the index method but returns none of the relationships in the show() method.
I always assumed that the protected $records variable was filled with the table data and its relationships and was used by the remained of the methods but I was VERY wrong.
Below is my resource controller and I would like to know if there are better templates to follow to eliminate having to recreate the ->with() from the index method for the show() method. Unlike the example below, often this grows VERY large and I don't want to have to "remember" to update the with() for both methods. Thanks!!
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
class UsersController extends ApiController
{
protected $records;
public function __construct(User $records)
{
$this->records = $records;
}
public function index()
{
// show all
$records = User::with('addresses', 'location', 'role', 'phones')->get();
return $records;
}
public function destroy($id)
{
// delete single
$record = $this->records->findOrFail($id);
$record->delete();
return $this->respondOK('User was deleted');
}
public function show($id)
{
//show single
$record = $this->records->findOrFail($id);
return $record;
}
public function store()
{
// insert new
$record = User::create(Input::all());
return $this->respond($record->id);
}
public function update($id)
{
// save updated
$record = $this->records->find($id);
if(! $record){
User::create(Input::all());
return $this->respond($record);
}
$record->fill(Input::all())->save();
return $this->respond($record);
}
}
The "with" function accepts arrays. I suggest creating an array in the constructor that may be shared in your methods. For example:
public function __construct(User $records)
{
$this->records = $records;
$this->related = ['addresses', 'locsation', 'role', 'phones'];
}
public function index()
{
// show all
$records = User::with($this->related)->get();
return $records;
}
@jgravois Have a look at route–model binding. Cuts out the need to query models in your controller actions, as the actions will be injected with model instances themselves.