0

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);
        }
}
3
  • what is the issue with the current approach? Commented Oct 15, 2022 at 4:54
  • In controller, I wil have more function where I must check if the browser is wrong. This is why I want to make CheckBrowser() - to avoid repeat same code, but I can't return view from here. My questions is if it possible? Commented Oct 15, 2022 at 5:02
  • that's what I am asking, what is the issue? You can do this way. Commented Oct 15, 2022 at 5:03

2 Answers 2

1

You can use the method redirect.

return redirect()->route('index');
Sign up to request clarification or add additional context in comments.

Comments

0

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 \App\Http\Controllers\Controller
{
    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');
    }
}

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.