Search code examples
phplaravel-5modelrestful-architecture

information about related models in Laravel


Hello I´m writing an API and I want to display more information about the related model.

Routes.php

Route::resource('makes', 'MakesController');

MakesController.php

class MakesController extends Controller
{
    public function index()
    {
        $data = Make::all();
        return response()->json($data);
    }
}

This returns only information about the makes (id, name) but how can I display also how many models has each make?

I have defined these two models

class Make extends Model
{
    public function models()
    {
        return $this->hasMany('App\CarModel');
    }
}


class CarModel extends Model
{
    public function make()
    {
        return $this->belongsTo('App\Make');
    }
}

Solution

  • You can define $visible field in the Make model's class like this:

    protected $visible = ['models'];
    

    This will automatically appends the related model's array to array/json.

    You can also use an optional way with makeVisible method:

    class MakesController extends Controller
    {
        public function index()
        {
            $data = Make::all();
            return response()->makeVisible('models')->json($data);
        }
    }