Search code examples
phplaravellaravel-livewirelaravel-jetstream

Adding card to Laravel Jetstream / Livewire profile form


I'm attempting to add a new profile section to the default laravel jetstream profile view. I've created a new livewire component called SetContactPreferences and am calling it from resources/views/profile/show.blade.php by adding:

@livewire('profile.set-contact-preferences') 

The form I created shows up as expected in the profile as a new card.

However, I'm unclear on what the submit action should look like. The docs say that the form will submit the current authenticated user as well as the form input, so I created a method in my component like:

public function setContactPreferences($user, $input) {
    dd($input);
}

I added <x-jet-form-section submit="setShowingPreferences"> to the top of the set-contact-preferences.blade.php file.

Submitting the form throws the following error:

Illuminate\Contracts\Container\BindingResolutionException
Unable to resolve dependency [Parameter #0 [ <required> $user ]] in class App\Http\Livewire\Profile\SetContactPreferences 

Solution

  • The way it works in Jetstream is that when the user profile information form is submitted, that submission is processed by the update method on the ProfileInformationController located at Laravel\Fortify\Http\Controllers\ProfileInformationController.

    The update method expects two parameters, a Request object and an UpdatesUserProfileInformation (which is an instance of App\Actions\Fortify\UpdateUserProfileInformation), both of which are injected from the service container.

    Jetstream obtains the current user from the Request object using $request->user() which is then passed to the UpdatesUserProfileInformation along with any form input using $request->input().

    If you are not concerned with other people updating user profile information (for example a system admin), you can type-hint a Request object in your method signature and it will automatically be injected:

    public function setContactPreferences(Request $request)
    {
        // Dump the currently authenticated user
        dd($request->user());
    }
    

    Alternatively you could provide your component with a User for scenarios where you might want to update the information of a user that is not the currently authenticated user.

    public User $user;
    
    public function setContactPreferences()
    {
        dd($this->user);
    }
    
    

    Then passing a User to the component:

    @livewire('profile.set-contact-preferences', ['user' => Auth::user()])
    

    or

    @livewire('profile.set-contact-preferences', ['user' => User::find(1)])