I want to check if a recipe belongs to the logged in user. The best way is middleware I guess.
So I created a middleware: AuthRecipe, containing the following code:
$repo = new RecipeRepository;
$recipe = $repo->getById($request->recipes);
if($recipe->user_id !== $request->user()->id)
{
return redirect()->to('/');
}
In the RecipeController I use the middleware like:
$this->middleware('auth.recipe', ['only' => ['update', 'edit', 'destroy']]);
This works fine, if the recipe doesn't belong to the user, the user gets redirected to home, but...
Now I have duplicated code. If the recipe belongs to the user, it will get the recipe inside the middleware, but also in the controller itself. So I already know the recipe and don't need to get the recipe again in the controller.
Of course I can use a method in the model itself.
public function auth() {
if($this->user_id !== Auth::user()->id) {
redirect()->to('/');
}
}
But then I have to call that method for every method that needs to be protected. I think the middleware is more cleaner. Calling $recipe->auth()
is not really a controller's responsibility.
Is there some way to pass the recipe data from the middleware to the controller?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire