Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel fortify CreateNewUser class how to customize


Laravel fortify CreateNewUser class how to customize


To customize the `CreateNewUser` class in Laravel Fortify, you can follow these steps:

1. Create a new file called `CreateNewUser.php` in your `app/Actions/Fortify` directory. This file should contain your customized implementation of the `CreateNewUser` class[1][3].

php
<?php

namespace App\Actions\Fortify;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Laravel\Jetstream\Jetstream;

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules;

    /**
     * Validate and create a newly registered user.
     *
     * @param  array  $input
     * @return \App\Models\User
     */
    public function create(array $input)
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => $this->passwordRules(),
            'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
        ])->validate();

        return User::create([
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => Hash::make($input['password']),
        ]);
    }
}

2. In your customized `CreateNewUser` class, you can modify the validation rules, add additional fields, or change the user creation logic as per your requirements[3].

3. If you need to pass additional parameters to the `create` method, you can modify the `CreatesNewUsers` interface in the same directory[1][2].

php
<?php

namespace App\Actions\Fortify;

interface CreatesNewUsers
{
    public function create(array $input, bool $makeValidation);
}

4. Update the implementation in your customized `CreateNewUser` class accordingly[1][2].

php
public function create(array $input, bool $makeValidation)
{
    // Your customized logic here
}

5. In your application, use the customized `CreateNewUser` class instead of the default one provided by Fortify[3].

php
use App\Actions\Fortify\CreateNewUser;

$user = app(CreateNewUser::class)->create($input, true);

By following these steps, you can customize the `CreateNewUser` class in Laravel Fortify to fit your specific requirements, such as adding additional validation rules, fields, or modifying the user creation logic.

Citations:
[1] https://stackoverflow.com/questions/70091389/how-to-modify-fortify-createsnewusers-php-interface
[2] https://laracasts.com/discuss/channels/laravel/how-to-modify-fortify-createsnewusersphp-interface
[3] https://laravel.com/docs/11.x/fortify
[4] https://laracasts.com/discuss/channels/laravel/why-modified-fortifycreatesnewusersphp-raise-error-from-standart-register-form
[5] https://www.youtube.com/watch?v=Vr4LJU3kw1g