lide's avatar
Level 1

Request attributes

In Laravel 5.1 in middleware I add custom attribute to request

$request->attributes->add(['company' => $company]);

And in Controller.php i have acces this with following code

use Illuminate\Http\Request;

public function __construct(Request $request) {
    $company = $request->get('company');
}

But now in Laravel 5.5 this not work anymore, any suggestions?

0 likes
10 replies
lide's avatar
Level 1

No, it not help. In L5.1 middleware run before control(tested with log event), but in L 5.5 not.

L5.1 Middleware

public function handle($request, Closure $next) {
    $company = \App\Companys::where('subdomain','=',$request->company)->where('active','=',1)->first();
    if($company) {
        $request->attributes->add(['company' => $company]);
        return $next($request);
    }
    return redirect('/');
}

L5.1 Controller.php

public function __construct(Request $request) {
    $request->get('company'); // return object correct
}

L5.5 Middleware

public function handle($request, Closure $next) {
    $company = CompanyModel::bySubdomain($request->subdomain);
    $request->attributes->add(['company' => $company]);
    return $next($request);
}

L5.5 Controller.php

public function __construct(Request $request) {
    $request->get('company'); // Not work
}

L5.5 CompanyModel bySubdomain method

public static function bySubdomain($subdomain) {
    return static::where('subdomain', $subdomain)->first();
}

All is made same way, but why L5.5 version is now After Middleware, not Before Middleware?

lewis4u's avatar

What is your $request? an array or a collection?

lide's avatar
Level 1

\Illuminate\Http\Request $request object

jaewun's avatar

Where are you adding the attribute to request?

I'm sure you shouldn't be modifying the Request object, is this the best way to be doing what you're trying to achieve?

lide's avatar
Level 1

I will add in middleware, check my 2nd comment, there is code.

In this middleware I check is there company in database with given subdomain, and I want pass this company object to controllers using later it.

lide's avatar
Level 1

My Middleware idea is check that database found company by given subdomain. I need this same data in many place so I want keep this data available in same request without make new query to database.

In Laravel 5.1 it work very well, but now in Laravel 5.5 it not work anymore :)

ThePlatinum's avatar

I had the same issue and this worked, even in the latest Laravel version as at the time of this response (L12)

$request->request->set(('key', $value);

Instead of $request->attributes.

Please or to participate in this conversation.