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

1.2k Views Asked by At

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.

3

There are 3 best solutions below

5
On BEST ANSWER

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?

3
On

You should use firstOrFail. This method will throw a 404 error if no user is found in the database.

Call to user column value with ->. So your code should look like this :

Route::get('/user/{username}', function($username){
    $user = User::where('username',$username)->firstOrFail();
    return view('viewname', ['user' => $user]);
}

Don't forget to create a view to your user page. You should also create a controller to handle thsi request.

0
On
$user = User::where('username', '=', $user)->first();

try with this..