Awa Melvine Awa Melvine - 1 month ago 13
JSON Question

Joining two database tables with laravel eloquent

I have two tables in my database:

Agency
and
Vehicle
. Each vehicle belongs to an agency and an agency has many vehicles. Here are my models:

Agency
model:

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Agency extends Model
{
protected $fillable = ['name', 'location'];

public function trains(){
return $this->hasMany('App\Vehicle');
}
}


Vehicle
model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Vehicle extends Model
{
protected $fillable = [
'agency_id',
'registration_number',
'description'
];

public function agency(){
return $this->belongsTo('App\Agency');
}
}


Now how can I return a json object with containing each
train
with its corresponding agency from my controller? Do I have to join the tables based on the agency_id? What is the best way to do this?

Thanks for any help :)

Answer

You can try it using with() and toJson() as:

Agency::with('trains')->get()->toJson();
Comments