Good I have 2 models in my Lumen project, one is Cars and the other Users, the relationship that I have defined is that 1 user can have N Cars
User Model
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as
AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as
AuthorizableContract;
use App\Traits\ActiveOrInactiveModelTrait;
use App\Traits\UserModelTrait;
class User extends Model implements
AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable, ActiveOrInactiveModelTrait, UserModelTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'status'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
];
/**
* Get all cars created by a user.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function pages_created()
{
return $this->hasMany('App\Cars', 'created_by');
}
}
Cars Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\ActiveOrInactiveModelTrait;
use App\Traits\PageModelTrait;
class Cars extends Model
{
use ActiveOrInactiveModelTrait, PageModelTrait;
protected $fillable = [
'title',
'brand',
'created_by',
'updated_by',
'status',
];
public $relationships = array('creator');
/**
* Get the user who created the car.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function creator()
{
return $this->belongsTo('App\User', 'created_by');
}
}
I have a controller that I do a getCarsFromUser that receives the User id as parameter and then in the controller I do something like this
try {
$user = User::find($id);
}
catch (\Exception $e) {
return response()->json([
'data' => new \stdClass(),
'response_text' => $e->getMessage()
], 500);
}
if ($user === null)
{
return response()->json([
'data' => new \stdClass(),
'response_text' => 'Resource Not Found'
], 404);
}
return response()->json([
'data' => $user,
'response_text' => 'OK'
], 200);
In principle if it finds the user it returns it to me along with the properties of the model along with a response 200, if the ID is null it returns me an answer 400.
This works, the only thing that when I return the property car returns an array of car, that is, car [1,3,11], which are the ids of the car model related to this user.
What I want to do is to return the JSON is to return all the user data together with all the data of each car, that is the doubt.