skip to Main Content

Route:

Route::controller(PublicController::class)->group(function () {
    Route::get('/index', 'index')->name('public.index');
});

View:

index.blade.php
wrong_browser.blade.php

In controller, this way is ok:

class PublicController extends Controller
{
    public function index(Request $request)
    {
        if(is_wrong_browser)
            return view(public.wrong_browser);
        
        return view('public.index');
    }
}

But how can I return view from another function, like this, without making a new route:

class PublicController extends Controller
{
    public function index(Request $request)
    {
        $this->CheckBrowser();
        
        return view('public.index');
    }
    
    public function CheckBrowser()
    {
        if(is_wrong_browser)
            return view(public.wrong_browser);
        }
}

2

Answers


  1. You can use the method redirect.

    return redirect()->route('index');
    
    Login or Signup to reply.
  2. You could use middleware which you either define globally, or on specific routes.

    class CheckUserActive
    {
        public function handle($request, Closure $next)
        {
            // determine value of $is_wrong_browser
            $is_wrong_browser = true;
    
            if ($is_wrong_browser) {
                    return redirect()->route('is-wrong-browser-route');
            }
    
            return $next($request);
        }
    }
    

    It is bad practice to return a view from middleware instead redirect your user to another route.

    Alternatively, you could have a base Controller that your Controllers extend which has the checkBrowser function defined on it and the extending Controllers therefore have access to:

    class WrongBrowserController extends AppHttpControllersController
    {
        public function checkBrowser()
        {
            // determine value of $is_wrong_browser
            $is_wrong_browser = true;
    
            if ($is_wrong_browser)
            {
                return view('wrong-browser-view');
            }
        }
    }
    
    
    class PublicController extends WrongBrowserController
    {
        public function index(Request $request)
        {
            $this->checkBrowser();
    
            return view('index');
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search