Description
You can organise these actions however you want. Personally, I like to place these under an app/Actions folder or — if my app is separated into modules — under app/MyModule/Actions.
namespace App\Authentication\Actions;
class UpdateUserPassword
{
public function handle(User $user, string $newPassword): void
{
$user->password = Hash::make($newPassword);
$user->save();
}
}
Next, add the AsAction trait to your class. This will enable you to use this class as an object, a controller, a job, a listener, a command and even as a fake instance for testing and mocking purposes.
namespace App\Authentication\Actions;
use Lorisleiva\Actions\Concerns\AsAction;
class UpdateUserPassword
{
use AsAction;
public function handle(User $user, string $newPassword): void
{
$user->password = Hash::make($newPassword);
$user->save();
}
}
The AsAction trait provides a couple of methods that help you resolve the class from the container and execute it.
// Equivalent to "app(UpdateUserPassword::class)".
UpdateUserPassword::make();
// Equivalent to "UpdateUserPassword::make()->handle($user, 'secret')".
UpdateUserPassword::run($user, 'secret');
Recent Courses on Laravel Daily
[NEW] Next.js Basics for Laravel Developers
11 lessons
58 min
Roles and Permissions in Laravel 13
14 lessons
57 min
How to Build Laravel 13 API From Scratch
30 lessons
1 h 23 min