Brijesh Dubey
Brijesh Dubey

Reputation: 118

How to Apply Multiple Middleware in Same method on Controller in Laravel 5.4

namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;

class UserProfileController extends Controller
{
    public function __construct(){
       $this->middleware('auth');
       $this->middleware('auth:admin');
    }
    public function show()
    {
        return view('user.profile.show');
    }
}

In this Controller I want to apply both middleware on show method. When I access this method using normal login, this displays content of view. But when I access this method using admin login, then this method redirects to normal login page.

Upvotes: 2

Views: 1581

Answers (1)

Brijesh Dubey
Brijesh Dubey

Reputation: 118

Hello guys,

I solved the issue.

I just create one

private method named as _show()

which is common for both

public method named as show() and showAdmin()

And

show() method for auth middleware And

showAdmin method for auth:admin middleware

Below is my code.

Controller page

namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;

class UserProfileController extends Controller
{
    public function __construct(){
       $this->middleware('auth',['only'=>['show'],'only'=>['showAdmin]]);
       $this->middleware('auth:admin',['only'=>['showAdmin'],'only'=>['show]]);
    }
    public function show()
    {
        $response = $this->_show();
        //Send $response to view
    }
    public function showAdmin()
    {
        $response = $this->_show();
        //Send $response to view
    }
    private function _show()
    {
        //Common logic
        //return 
    }
}

View page

@if(Auth::check())
{--Goto show method via route--}
@else
{--Goto showAdmin method via route--}
@endif

I think it's helpful for someone who want to use middleware in Laravel 5.4

Thank you

Heart to try.it work

Upvotes: 1

Related Questions