Why isn't my user data passing to page view using show method in resource controller?

Viewed 110

I want to return a profile with full name and username, but when I try to pass the data, those fields disappear when the view loads up.

In my Profiles Controller I tried the following:

public function show(User $user)
    {
        return view('profile')->with(['user' => $user]);
    }

I also tried:

public function show(User $user)
    {
        return view('profile', compact('user));
    }

And also tried:

public function show(User $user)
    {
        return view('profile', ['user' => $user]);
    }

And yes, I already have use App\Http\Controllers\ProfilesController; as I made controller with this command php artisan make:controller ProfilesController --resource --model=Photo

My resource route in web.php is:

Route::resource('/profile', ProfilesController::class)->names([
    'show' => 'profile.show'
])

The view is loading up fine, just without the data to passed in.

<div class="profile_full_name_div">
    <p class="profile_full_name">{{ $user->name }}</p>
</div>

<div class="profile_username_div">
    <p class="profile_username">{{ $user->username }}</p>
</div>

Whenever I put in a hardcore name, the username and full name info would reappear into the view. For example:

<div class="profile_full_name_div">
    <p class="profile_full_name">Susan Bowe</p>
</div>

<div class="profile_username_div">
    <p class="profile_username">susan_bowe</p>
</div>
1 Answers

When injecting a model ID to a route or controller action, you will often query the database to retrieve the model that corresponds to that ID. Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user's ID, you can inject the entire User model instance that matches the given ID.

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name. For example:

use App\Models\User;

Route::get('/users/{user}', function (User $user) {
    return $user->email;
});

Since the $user variable is type-hinted as the App\Models\User Eloquent model and the variable name matches the {user} URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated.

However if you declare the route without this parameter Laravel will not be able to resolve the correct user, and therefore no data is sent to your view. Because the model is empty.

You can check this by doing a dd() in your controller.

Related