I want to make an instant redirection in my controller in Laravel.
I know I can use
public function show($page)
{
return Redirect::url(\'http://ex
You have to return the results of the method in the base controller.
return $this->checkPages($page, $totalPages, 'http://example.com');
After a while of digging it seems that for this purposes you should use send()
method from Symfony\Component\HttpFoundation
(Laravel RedirectResponse
inherits from this class).
So you can modify checkPages
method this way:
public function checkPages($page, $totalPages, $url)
{
if ($page < 2 or $page > $totalPages) {
Redirect::url($url)->send();
}
}
and it will make instant redirection.
I'd probably suggest that your checkPages
method is trying to do too much. Would I expect checkPages
(which maybe should be validatePageNumber()
or similar) to return a redirect? No, I'd expect it to return true
or false
.
That gives you this as your logic:
/**
* Make sure the current page is between 1 and $lastPage
*
* @param int $page
* @param int $lastPage
* @return bool
*/
protected function validatePageNumber( $page, $lastPage ) {
return $page < 2 || $page > $lastPage;
}
and now your controller logic is trivial:
public function show( $page ) {
$totalPages = 100;
if ( ! $this->validatePageNumber( $page, $totalPages ) ) {
return Redirect::url( 'http://example.com' );
}
// rest of code here - should be run if condition is false
}
Now if we use quasi-English to read your code, you have a public method show($page)
which shows a page: it sets the total number of pages, checks that $page
is valid, and if not, redirects somewhere. All of this is control logic, and only control logic, which is what a controller should be doing.
Your validatePageNumber()
can now be abstracted into a model, or better yet, a ServiceProvider, and it does one job: validates that a number is between 1 and n
.