How can I redirect application to specific url from my custom class?
Let's say I have my custom class API in Laravel Application:
class API {
private function generic_request( $uri )
{
$response = $this->getResponse($uri);
if($response == 'bad_token')
{
//redirect to login screen with message
}
}
In my controller function:
public function add_employee() {
$data['employee_positions'] = API::generic_request('/employees/position_list');
$this->layout->content = View::make('employees.add_employee')->with($data);
}
I've tried Events
, but you can't redirect from Event
listener. Right now I'm using Exceptions
but I feel like it's wrong approach. For example:
App::abort(401);
and then in global.php
:
App::error(function(Exception $exception, $code)
{
/*CORE API Exceptions*/
if($code == 401)
{
Session::put('message','System Action: Expired Token');
return Redirect::to('login');
}
}
You just have to create a response and return it all the way back to Laravel:
<?php
class API {
public function doWhatever($uri)
{
return $this->generic_request($uri);
}
private function generic_request( $uri )
{
$response = $this->getResponse($uri);
if($response == 'bad_token')
{
return Redirect::to('login')->with('message', 'your message');
}
}
}
Route::get('test', function()
{
return with(new API)->doWhatever('yourURI');
});
With Laravel 5.7 you can use the what @casft originally mentioned like this -
abort(redirect('login')->with('alert-warning', 'Your session token has expired. Please login to continue.'));
When you are not using the laravel traditional Auth and rely on a bearer tokens for authentication, moreover you want to prevent your public functions from code smell then you can filter on 401 http response call with this handy function. May not be the best or elegant solution but gets the job done.