jeudi 26 novembre 2015

Laravel BelongsTo and hasOne Model Relationship returns Null

I am wondering why my Models returns null when requested record does not exist in database table instead of returning empty collection or empty Model instance.

Here are my models

class User extends Model implements AuthenticatableContract,   AuthorizableContract, CanResetPasswordContract
{
     use Authenticatable, Authorizable, CanResetPassword;

     protected $softDelete = true;

     protected $fillable = [
         'id',
         'email',
         'password',
         'first_name',
         'last_name',
         'state_id'
     ];


     public function state(){
          return $this->belongsTo('App\Models\State','state_id','id');
     }

}



class State extends Model{

     protected $fillable = [
           'name',
           'country_id',
           'active',
    ];
}

States Table

 id   name  country_id  active

 1   texas    1           1

 2   alaska   1           1

Users Table

 id   first_name  state_id

 1    frank        null

Here is the problem or is this how it's meant to behave?

$user = User::with('state')->get(); //returns null

I expected Laravel to return an empty Collection when state_id of a user does not exist in states table instead null is being returned,

The issue I have with this is, I am using a Transformer which expects an instance of state model and not a null

public function includeState(User $model)
{
    $state = $model->state; //null is being returned here
    return $this->item($state, new StateTransformer); //this throws an exception when it receives null
}

see: http://ift.tt/1e6CG73



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire