Laravel authorize() assigns unexpected object to response

  eloquent, laravel, laravel-authorization, php

I have three Eloquent models for a recipe management application, where User has many cookbook, cookbook has many recipes and so on (see below). To authorize I’m using this policy:

public function view(User $user, Recipes $recipe) {
    return $user->id === $recipe->cookbook->user_id;
}

Here is the controller

public function show($id) {
    $recipe = Recipes::find($id);
    $this->authorize('view', $recipe);
    return $recipe;
}

Testing this works fine, however I’m getting extra information in my response.
Unexpected Result vs. Expected Result (Sorry I don’t have enough reputation to post images)

The response somehow gets assigned an extra object ‘cookbook’. After print testing the problem seems to lie on the line $recipe->cookbook->user_id; where if removed the result came to be as expected. Am I overlooking something?

Models for Reference

  1. User
class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function cookbooks() {
        return $this -> hasMany('AppModelsCookbook');
    }

    public function recipes() {
        return $this -> hasManyThrough('AppModelsRecipes', 'AppModelsCookbook');
    }
}

  1. Cookbook
class Cookbook extends Model
{
    use HasFactory;

    protected $guarded = ['user_id'];
    protected $fillable = [
        'cookbook_name',
    ];

    protected $casts = [
        'cookbook_shared_user' => 'string'
    ];

    public function user() {
        return $this-> belongsTo('AppModelsUser');
    }

    public function recipes() {
        return $this -> hasMany('AppModelsRecipes');
    }
}

  1. Recipe
class Recipes extends Model
{
    use HasFactory;

    protected $guarded = ['cookbook_id'];
    protected $fillable = [
        'recipe_name',
        'recipe_description',
        'recipe_video_url',
        'recipe_image_url'
    ];

    public function cookbook() {
        return $this -> belongsTo('AppModelsCookbook');
    }
}

Source: Laravel

Leave a Reply