A
A
Arman2019-09-06 13:52:29
Laravel
Arman, 2019-09-06 13:52:29

How to pass object from middleware to controller in Laravel?

For some reason, I’m more than sure that there are people who have met with such a task, but somehow I haven’t found a solution, Google suggests that many people shove data into request and pull it out from there ($request->object), but somehow it can be a dependency substitute?
I would like something like this:

// Url: site.tld/username/profile
// Url: site.tld/username/posts
// Url: site.tld/username/comments

// routes
Route::prefix('{userLogin}')
    ->name('user.')
    ->middleware('user.login')
    ->group(*);

// Middleware
public function handle($request, Closure $next) 
{
    $user = User::where('login', $request->segment(1))->findOrFail();
    app('url')->defaults(['login' => $user->login]);
    *set_data*('currentUser', $user);

    return $next($request);
}

// controller
public function show(User $currentUser)
{
}

After that there will be more complex logic, I would like to solve exactly the middleware, so that in each action controller this would not be solved =/

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Nikolaev, 2019-09-06
@Arik

Middleweirs are not meant to be stuffed into a controller. They process the request and either pass it to the next middleweir (and so on until the end), or return a response (which will abort the execution).
If you write this infernal bike just to authorize users and get the current user's instance, then in Lara this is already implemented out of the box .

K
Konstantin B., 2019-09-06
@Kostik_1993

Route Model Binding solves your problem correctly

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question