Subhajit
Subhajit

Reputation: 894

Laravel Middleware : Call to a member function header() on array

In my project there are two levels of middleware.

One UserAuthentication, and another is PermissionsMiddleWare.

Suppose there is a route :

Route::group(['middleware' => ['myauth', 'revalidate'], 'prefix' => '/user'], function () {
    Route::group(['middleware' => 'permissions:Campaigns'], function () {
      Route::resource('/dashboard', 'UserController@dashboard');
    }
}

Now in UserAuthenticationMiddleware:

     <?php
public function handle($request, Closure $next)
{
    if ($request->session()->has('user_id')) {
        $user_id = $request->session()->get('user_id');
    } else {
        return redirect('loginUser');
    }

    $response = $next($request);
    return $response->header('Cache-Control', 'nocache, no-store, max-age=0, must-revalidate')
            ->header('Pragma', 'no-cache')
            ->header('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT');

    return $next($request);
}

And in PermissionsMiddleware:

<?php
public function handle(Request $request, Closure $next, $permission_name = "")
{
//login to get permission decision
    if (!$decision) {
// **Old process** of response
// return redirect('user/accessRejected')->with('message', 'Request rejected');
// **New process** of response
        return ['accessRejected' => true, 'message' => 'Request rejected'];
    }


    $response = $next($request);
    return $response->header('Cache-Control', 'nocache, no-store, max-age=0, must-revalidate')
            ->header('Pragma', 'no-cache')
            ->header('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT');

    return $next($request);
}

Old process is working fine, and permissions middleware is restricting properly and redirecting to the page.

Now, as this is API side of project , so I cannot redirect to another page rather I need to response in JSON or array format.

When following the new process of response I am getting this error:

FatalErrorException in UserAuthenticationMiddleware.php line (this below code line):
-> return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')
            ->header('Pragma','no-cache')
            ->header('Expires','Fri, 01 Jan 1990 00:00:00 GMT');
Call to a member function header() on array

Please give some light on this to know what is wrong in my code.

Upvotes: 1

Views: 4551

Answers (1)

Subhajit
Subhajit

Reputation: 894

Instead of returning only the data we can use return response with data. Like this :

return response(['accessRejected'=> true, 'message'=>'Request rejected reason:' . $this->checkPermission]);       
 }

Then we can get the response properly.

Upvotes: 1

Related Questions