Laravel's redirect route doesn't work using return, but if I use echo it works why?

Hi guys 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)

doesnt. Does anyone know why?

+3


source to share


2 answers


You need to understand the difference between return

andecho

  • return

    : when you call a method from another method and you return some data, the returned data replaces the method.
  • echo

    : when you use echo, it won't return some data to the caller or main function, but it will display the data directly.

Example

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

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

      

The above codes do not display anything on the user's screen because you have not added a display code to any of the functions.

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!

Going back to your question, you need to either trace the call forwarding in the called method, or return the returned call forward in the caller's 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 correctly. Hope this was helpful to you ...

+2


source


Your code works great.

I think 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 with HomeController

your controller. Make sure you don't delete /{routeName}

if you want to change the URL.

Example: localhost:3000/test/admin.login

will open the admin login page as the route name admin.login

is as shown in the above code.

0


source







All Articles