2

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.

7
  • You can add middlewares via route too, and there you can set multiple middlewares. Also you can do this in construct $this->middleware('admin')->only('show') Commented May 17, 2017 at 11:53
  • Are you sure role middleware is working perfectly? Commented May 17, 2017 at 11:54
  • yes but i want to use in controller Commented May 17, 2017 at 11:55
  • i am also try this way also $this->middleware('auth',['only'=>['show']]); $this->middleware('auth:admin',['only'=>['show']]); Commented May 17, 2017 at 11:56
  • but its work only for one middleware not both Commented May 17, 2017 at 11:57

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.