phplaravellua-5.3

laravel get user info by routing to '/user/{username}' Not Working


i am new to laravel and i am having trouble getting the user info by going to the route 'user/{username}';

theoretically it should work, this is my route:

Route::get('/user/{username}', function($username){
    $user = User::where('username',$username) -> first();
    if(isset($user['username'])){

        return redirect()->route('/user/'.$username, ['user' => $user]);

    }else{

        return redirect()->route('/user/'.$username, ['error' => 'This User Does Not Exist']);

    }
});

i did use App\User; in the page so it should work. i am getting this error:
NotFoundHttpException in RouteCollection.php line 161:

Any help is appreciated, thank you, please let me know if u need any more information in order to help.


Solution

  • Redirect takes a routes name, not the path you wish to redirect to. In your code, add a name for your route, like this:

    Route::get('/user/{username}', function($username) {
        [...]
    })->name('username');
    // Here we call our route 'username'
    

    Now you can do redirect like this:

    // Note that we call redirect with the name we just gave it, passing the username value forward
    return redirect()->route('username', ['username' => $user]);
    

    Edit: Looking at your code I do not fully understand what you wish to do. The code looks like it would create a redirect loop? It looks like if you find a user, you redirect back to the same route?