Laravel / Lumen - Serialize an object

1

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.

    
asked by ilernet 20.02.2018 в 13:05
source

1 answer

2

As we can see in the documentation ( link ) Laravel by default does not load the data of the relationships until they are not necessary.

For example in the case of the question

// Obtenemos la fila, pero no los datos de sus relaciones
$user = User::find($id); 

// Al recorrer la relación es cuando se obtienen los datos
foreach ( $user->relacion as $fila) {
    echo $fila->campo;
}

It is appropriate to indicate that in the previous case Laravel will make 1 + N queries , that is, a query to obtain the main record and one more query for each row of the relation.

There is a case in which we are interested in obtaining all the data of the pull, without waiting for these to be necessary or traveled or if we know in advance that all the data of the relationship will be necessary.

For these cases we can use the with() method of Laravel. This will bring us all the data of the row and its relation in only 2 queries .

Example

 $user = User::where('id', $id)->with('relacion')->get();

In this case the data of the relation will be brought immediately after bringing the row of the model User

    
answered by 22.02.2018 / 13:58
source