![Theme Switcher Image](https://stackcoder.in/images/theme-switcher.png?cb=stackcoder90070)
Good content takes time and effort to come up with.
Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.
Most of the time, you would be facing problems when you might want to redirect from called functions.
But this article I will show you a simple way to force URL redirect from other functions in Laravel.
Assume you are developing multi-tenancy application, and you have custom designed your login system and don't want login user to see login page, then you would do something like the following in AuthController
.
It just checks for the user session and redirects to the default landing page as per the user role.
Calling Function
- AuthController -> login()
Called Function
- Controller -> loginRedirect()
class AuthController extends Controller
{
public function login()
{
/** Login Redirect Is Handled From Controller class */
$this->loginRedirect();
return view('auth.login');
}
}
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function loginRedirectLink()
{
/** If admin redirect to dashboard URL else customers URL */
$role = session()->get('user_details')->role;
return ($role == 'admin') ? 'dashboard' : 'customers';
}
public function loginRedirect()
{
/** Check if user is already logged in if yes then redirect accordingly */
if (session()->has('user_details')) {
redirect($this->loginRedirectLink());
}
}
}
Basically, if you useredirect()->to('some_link')
orredirect('some_link')
, then redirect of URL will be returned to CALLING FUNCTION and won't redirects from CALLED FUNCTION.
redirect($this->loginRedirectLink());
With the help of redirect()->to('url')->send()
we will force redirect the url from CALLED FUNCTION
redirect()->to($this->loginRedirectLink())->send();
class Controller extends BaseController
{
/** ** Other Code ** */
public function loginRedirect()
{
if (session()->has('user_details')) {
redirect()->to($this->loginRedirectLink())->send();
}
}
}
I hope this article helped you. Please share it with your friends.
Why You Should Run Cronjobs In Laravel?
Laravel Last Executed Query In Plain SQL Statement For Debugging
@stack @push and @prepend In Laravel Blade
Setup MAMP Virtual Hosts For Local PHP Development
Client-Side Form Validation With Javascript
Use Different PHP Versions In Ubuntu / Linux
Upload File From Frontend Server {GuzzleHttp} To REST API Server In PHP {Laravel}
Testing Laravel Emails With MailHog
Client-Side DataTable, Adding Super Powers To HTML Table
Google, Twitter, GitHub, Facebook & Many Other Social Generic Logins With PHP Laravel Socialite
GitHub Login With PHP Laravel Socialite
Create / Save / Download PDF From Blade Template In PHP Laravel