2
I have the following middleware:
class OwnerOrAdmin
{
public function handle($request, Closure $next)
{
$user = \Auth::user();
$postId = $request->route('post');
$post = $user->posts->find($postId);
if ($user->id == 1 || (!is_null($post) && $post->user_id == $user->id)) {
return $next($request);
}
return redirect()->route('post.index')
->with(['status' => 'danger', 'mensagem' => 'Este post não te pertence!']);
}
}
Basically this check if the user who will edit a post is Admin (id=1) or if this is the owner of the post.
But in my controller I have to repeat practically the same query to the bank:
public function edit($id)
{
$post = Post::find($id);
return view('painel.post.cad-edit', compact('post'));
}
It would be possible to pass this value to the controller as return from middleware?
The best way to do this is by using Authorization instead of middleware. https://laravel.com/docs/5.3/authorization
– gmsantos
Later I’ll give you an answer.
– gmsantos
Had done via Authorization, however, I did not like the result very much. Via middleware I can validate and already indicate the return message applied only the routes (Resource) store, update and Destroy. When I did via Authorization I had to "modify" the controller, something I would like to avoid if possible
– Fábio Jânio
Tried to do via Form Request?
– gmsantos
In this case, I wouldn’t answer. For example, on Edit and Destroy I need to pass only the registry id, so it wouldn’t make much sense to inject a custom Request.
– Fábio Jânio
Seria possível passar este valor para o controller como retorno do middleware?
I saw that question and I read it, I reread it, but seriously nay It’s like, anything made for it can get weird (gambiarra), up to yourmiddleware
should return an error not aredirect
(should not be a rule), maybe (I repeat maybe) make acache
to optimize bank research, but I have never testedEloquent
. If you’re worried maybe about the repetition ofSQL
(select * from posts where id = 1
)in this case there are not so many problems and the repetition of the code are at different times– novic