pinoyCoder
pinoyCoder

Reputation: 1370

Laravel redirect route is not working using return but if i use echo its working why?

I got this weird experience with laravel redirect->route('routeName'). Here is the code:

public static function loginCheckWithRedirect($routeName = false){

    if(functions::loginCheck()){
        if($routeName && is_string($routeName)){
            return redirect()->route($routeName);
        }
    }

    return false;
}

If I use echo redirect()->route($routeName), it works. But return redirect()->route($routeName) does not. Why?

Upvotes: 2

Views: 1513

Answers (2)

Kamga Simo Junior
Kamga Simo Junior

Reputation: 1741

You need to understand the difference between return and echo

  1. Return: when you call a method from another method, and you return some data, the return data will take the place of the method called.
  2. Echo: when you use echo, it will not return some data to the calling or main function but it will display the data directly.

Example

function myFun($param){
    return $param;
}

function ini(){
    myFun("Hello!");
}

The above codes will display nothing on the user's screen because you did not add a display code in any of the function.

But if you use either:

function myFun($param){
    return $param;
}

function ini(){
    echo myFun("Hello!");
}

Or:

function myFun($param){
    echo $param;
}

function ini(){
    myFun("Hello!");
}

The output will be Hello!

Coming back to your question, You need to either echo the redirect call in the called method or you return the returned redirect call in the caller method

This is what I did:

Route file

    use App\Http\Controllers\TestController;

Route::get('/', function(){
    return TestController::loginCheckWithRedirect('myRoute');
});

Route::get('/test', function(){
   return 'Redirected...';
})->name("myRoute");

TestController

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    public static function loginCheckWithRedirect($routeName = false){

        if(functions::loginCheck()){
            if($routeName && is_string($routeName)){
                return redirect()->route($routeName);
            }
        }

        return false;
    }
}

The above code redirects properly. Hope this was helpful to you...

Upvotes: 1

Kofi Mokome
Kofi Mokome

Reputation: 189

Your code works perfectly.

I guess the problem is with your route file (web.php if you are using laravel 5.4).

This is what I did:

Route::get('/test/{routeName}','HomeController@loginCheckWithRedirect')->name('test');
Route::get('/admin/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');

Replace HomeController with your controller. Make sure not to remove /{routeName} if you want to change the url.

Example : localhost:3000/test/admin.login will open the admin login page since the route name is admin.login as seen in the code above.

Upvotes: 0

Related Questions