Laravel - How to pass arguments to function in route controlller?

60 views Asked by At

I am using Laravel Fortify to register my users. I have multiple kinds of users.

Below is the code to access the registration controller :

 Route::post(
      RoutePath::for('register', '/register'),
      [RegisteredUserController::class, 'store']
 )->middleware(['auth.already:'.config('fortify.guard')]);

Now, if we inspect the controller, that's what we have :

public function store(Request $request, CreatesNewUsers $creator): RegisterResponse
{
    if (config('fortify.lowercase_usernames')) {
        $request->merge([
            Fortify::username() => Str::lower($request->{Fortify::username()}),
        ]);
    }

    event(new Registered($user = $creator->create($request->all())));

    $this->guard->login($user);

    return app(RegisterResponse::class);
}

I'd like to understand how I might change the value of the $creator argument in order to pass my own class.

I was unable to find any help in the Laravel / Laravel Fortify documentation.

1

There are 1 answers

0
Harshad Kanani On BEST ANSWER
  • Create your own class that implements the 'CreatesNewUsers' interface. Let's call it 'YourCustomCreateUser'
namespace App\Services;
use Laravel\Fortify\Contracts\CreatesNewUsers;

class YourCustomCreateUser implements CreatesNewUsers
{
    public function create(array $input)
    {
        // Your custom logic for creating a new user
    }
}
  • Bind your class to the 'CreatesNewUsers' interface in your 'AppServiceProvider' or any service provider.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\YourCustomCreateUser;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(CreatesNewUsers::class, YourCustomCreateUser::class);
    }
}
  • Make sure to adjust the namespace and class names according to your application's structure.