skip to Main Content

Trying to show the current signed in user’s profile. What am i doing wrong.This is the function on the controller. I’m using Laravel 9

public function show(User $user)
{
    return view('users.index', with('user', $user));
}

This is the routes

    Route::resource('users', UsersController::class)->middleware('auth');

And my generic layout page

<x-dropdown-item href="/users/{{ auth()->user()->username }}" >Account</x-dropdown-item>

When i click the link i get user not found.

3

Answers


  1. You’re utilising route model binding which unless configured otherwise, requires you to provide a route with a model id. You’re providing it with a username, so Laravel is throwing a 404 because it can’t locate the relevant record in the database.

    If you replace username with id, the binding should work.

    <x-dropdown-item href="/users/{{ auth()->user()->id }}">
        Account
    </x-dropdown-item>
    
    Login or Signup to reply.
  2. The code is fine. Are you sure you have a route with username, resource routes are using id.

    Login or Signup to reply.
  3. To access model like that you need to specify id in the route like:
    /users/{id}

    However what you are trying to do here is access the logged in user model which you can access with the facade Auth::user();

    You can access the user any time any where in the code and there is no need to pass it to an anchor link unless sending to an external system.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search