Laravel authorize() 将意外对象分配给响应

Laravel authorize() assigns unexpected object to response

我有一个食谱管理应用程序的三个 Eloquent 模型,其中 User 有很多 cookbookcookbook 有很多 recipes 等等(见下面)。

授权我使用此政策:

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

这是控制器:

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

    return $recipe;
}

测试这个工作正常,但是我在回复中得到了额外的信息。

响应以某种方式被分配了一个额外的对象cookbook。打印测试后,问题似乎出在行 $recipe->cookbook->user_id; 上,如果将其删除,结果会如预期的那样。

我是不是忽略了什么?

参考模型

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('App\Models\Cookbook');
    }

    public function recipes() {
        return $this->hasManyThrough('App\Models\Recipes', 'App\Models\Cookbook');
    }
}

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('App\Models\User');
    }

    public function recipes() {
        return $this->hasMany('App\Models\Recipes');
    }
}

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('App\Models\Cookbook');
    }
}

您正在 policy 中加载关系,正是您所说的位置:

$recipe->cookbook

现在在您的控制器中,您可以将 return 更改为:

return $recipe->setAppends([]);

这将删除您的附加项,例如 cookbook

如果你想要更多的控制,你可以使用 API Resources(Laravel 方式)。