Last active
September 3, 2025 22:23
-
-
Save ahosker/6d0d6bbeb1b87f5de74a5754e44c9cad to your computer and use it in GitHub Desktop.
Laravel Boost Guidelines for Laravel Actions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace {{ namespace }}; | |
| use App\Http\Requests\Store{{ class }}Request; | |
| use Illuminate\Console\Command; | |
| use Lorisleiva\Actions\Concerns\AsAction; | |
| use Lorisleiva\Actions\Concerns\WithAttributes; | |
| class {{ class }} | |
| { | |
| use AsAction; | |
| use WithAttributes; | |
| // Command signature (kebab-case, descriptive) (e.g., "user:set-role") | |
| // Adjust per action domain if needed. | |
| public string $commandSignature = '{{ class }}:{{ class }}'; | |
| // execute action as `php artisan {{ class }}:{{ class }}` | |
| public string $commandDescription = '{{ class }} Description'; | |
| // Unified attributes (limit to the requested fields) | |
| public mixed $input_1 = null; | |
| public ?string $input_2 = null; | |
| public function authorize(): bool | |
| { | |
| return (new Store{{ class }}Request)->authorize(); | |
| } | |
| // {{ class }} Unified Attributes, input rules. | |
| public function rules(): array | |
| { | |
| $rules = (new Store{{ class }}Request)->rules(); | |
| return Arr::only($rules, ['input_1', 'input_2']); | |
| } | |
| // Handle receives raw attributes, fills, validates, and delegates to actionLogic | |
| public function handle(array $attributes = []): object | |
| { | |
| $this->fill($attributes); | |
| $this->validateAttributes(); | |
| // {{ class }} Main Action Logic Call | |
| $response = (object) $this->actionLogic(); | |
| return $response; | |
| } | |
| // Console entrypoint | |
| public function asCommand(Command $command): int | |
| { | |
| $attributes = [ | |
| 'input_1' => $command->ask('{{ class }} question?', '{{ class }} answer'), | |
| 'input_2' => $command->ask('{{ class }} question 2?', '{{ class }} answer 2'), | |
| ]; | |
| $response = $this->handle($attributes); | |
| // Return Response Confirmation | |
| $command->info('Action: {{ class }} Done!'); | |
| return 0; | |
| } | |
| // Core business logic - use Unified Data. | |
| private function actionLogic(): object | |
| { | |
| // {{ class }} Action Logic Here | |
| $input_1 = $this->get('input_1'); | |
| $input_2 = $this->get('input_2'); | |
| // Return Response as object. | |
| return (object) [ | |
| 'success' => true, | |
| 'data' => [] | |
| ]; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <laravel-actions-rule> | |
| === laravel actions rule === | |
| No business logic will exist in Laravel Livewire Controllers only called from them, it will exist in a Laravel | |
| Action Class. | |
| Use snake_case wherever possible for variable and method names. | |
| # Generating a New Laravel Action (sh) | |
| - Never manualy create a Action File. | |
| - Always use `php artisan make:action` to generate the PHP file. | |
| Example: | |
| ```bash | |
| php artisan make:action User\SetRoleAction | |
| ``` | |
| # Design | |
| - Actions should be designed to be reusable and composable. | |
| - Each action should have a single responsibility and should not be overly complex. | |
| - Use input validation and authorization within actions to ensure data integrity and security. | |
| - Always, have a `handle` method that invokes the `actionLogic` method. | |
| - Always, have a `asCommand` to run the action from the command line. | |
| - Always, have a `actionLogic` method that contains the main logic of the action. | |
| - Always, implement a Laravel Action with Unified Attributes. | |
| - Never, have a `asController` method to run the action from a controller (we use livewire), unless absolutly | |
| necessery. | |
| # using handle | |
| - Always, have a `handle` method. | |
| - The `handle` method will accept attributes as an array and objects such as `User $user` | |
| - The `handle` method will handle the inputs. | |
| - The `handle` method will invoke the main logic of the action at `$this->actionLogic`. | |
| # using asCommand | |
| - Always, have a `asCommand` to run the action from the command line. | |
| - Always, have `$command->ask('Question?');` line to prompt the user for input, try to have defaults for testing. | |
| - Always, have a `$command->info('Action X Done!');` line to indicate successful completion. | |
| - Always, have a `commandSignature` following class name and location e.g. `user:update-role` | |
| # Using asController | |
| Typically Unnecessary, as we use Livewire for Controllers. | |
| # Using actionLogic | |
| - Always, have a `actionLogic` method that contains the main logic of the action. | |
| - The `actionLogic` method will use unified objects such as `$this->input_1` and `$this->input_2`. | |
| - The `actionLogic` method will return a response object. | |
| # Using Commands | |
| - Pass `--no-interaction` to all Artisan commands to ensure they work without user input. | |
| </laravel-actions-rule> | |
| <laravel-actions-code-snippets> | |
| ======================== | |
| LARAVEL ACTIONS CODE SNIPPETS | |
| ======================== | |
| TITLE: Generating IDE Helper Actions File (Artisan) | |
| DESCRIPTION: This Artisan command generates the `_ide_helper_actions.php` file. This file is crucial for IDEs to | |
| provide | |
| accurate autocompletion and type hinting for your Laravel Actions, improving the development experience after | |
| installing | |
| the IDE helper package. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/installation.md#_snippet_3 | |
| LANGUAGE: sh | |
| CODE: | |
| ``` | |
| php artisan ide-helper:actions | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Installing Laravel Actions via Composer (sh) | |
| DESCRIPTION: This command adds the "lorisleiva/laravel-actions" package as a dependency to your Composer project. | |
| It's | |
| the first step to integrate Laravel Actions into your application, ensuring all necessary files are downloaded and | |
| available. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/installation.md#_snippet_0 | |
| LANGUAGE: sh | |
| CODE: | |
| ``` | |
| composer require lorisleiva/laravel-actions | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Installing Laravel Actions Package (Composer) | |
| DESCRIPTION: This command installs the core Laravel Actions package via Composer, adding it as a dependency to your | |
| project. It's the first step to integrate Laravel Actions into your application. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/installation.md#_snippet_0 | |
| LANGUAGE: sh | |
| CODE: | |
| ``` | |
| composer require lorisleiva/laravel-actions | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Using Dedicated Actions for Form Display and Submission (PHP) | |
| DESCRIPTION: This example illustrates an alternative approach where a dedicated action ('ShowNewArticleForm') is | |
| used | |
| solely for displaying a form via a GET request, while a separate action ('CreateNewArticle') handles the form | |
| submission | |
| via a POST request. This promotes better organization by separating concerns into distinct actions. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/register-as-controller.md#_snippet_9 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| Route::get('/users/{user}/articles/create', ShowNewArticleForm::class); | |
| Route::post('/users/{user}/articles', CreateNewArticle::class); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Adding Middleware Directly to Laravel Action (PHP) | |
| DESCRIPTION: This example demonstrates how to define middleware directly within a Laravel Action class using the | |
| `getControllerMiddleware` method. This approach centralizes middleware configuration for the action, making it more | |
| self-contained and easier to manage than defining middleware in the routes file. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/examples/get-user-profile.md#_snippet_3 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| class GetUserProfile | |
| { | |
| use AsAction; | |
| public function getControllerMiddleware(): array | |
| { | |
| return ['auth', MyCustomMiddleware::class]; | |
| } | |
| // ... | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Generating a New Laravel Action (sh) | |
| DESCRIPTION: This Artisan command creates a new action class named "MyFirstAction" within the "App\Actions" | |
| namespace. | |
| It provides a boilerplate structure for defining authorization, validation rules, and the main execution logic of | |
| the | |
| action. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/installation.md#_snippet_1 | |
| LANGUAGE: sh | |
| CODE: | |
| ``` | |
| php artisan make:action MyFirstAction | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Using asController Before Hook for Action Preparation in PHP | |
| DESCRIPTION: This code illustrates the `asController` before hook, which executes specific logic only when the | |
| action is | |
| run as a controller. Similar hooks exist for other execution types (e.g., `asJob`, `asListener`), allowing for | |
| type-specific setup or data preparation, and they support dependency injection. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/action-running-as.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| public function asController(Request $request) | |
| { | |
| $this->token = $request->cookie('token'); | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Running a Laravel Action as a Plain Object - PHP | |
| DESCRIPTION: This example demonstrates instantiating a `PublishANewArticle` action as a plain PHP object, passing an | |
| array of data to its constructor. The `run()` method is then called to execute the action's `handle` method, | |
| returning | |
| the result. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/basic-usage.md#_snippet_1 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| $action = new PublishANewArticle([ | |
| 'title' => 'My blog post', | |
| 'body' => 'Lorem ipsum.', | |
| ]); | |
| $article = $action->run(); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Publishing Laravel Action Stub (Artisan) | |
| DESCRIPTION: This Artisan command publishes the default stub used by the `make:action` command. Publishing the stub | |
| allows developers to customize the template for newly generated action classes, tailoring them to specific project | |
| conventions or requirements. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/installation.md#_snippet_4 | |
| LANGUAGE: sh | |
| CODE: | |
| ``` | |
| php artisan vendor:publish --tag=stubs --provider="Lorisleiva\Actions\ActionServiceProvider" | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Invoking Laravel Action as Controller (Example) | |
| DESCRIPTION: This snippet demonstrates how an action can be invoked directly like a function, which is syntactically | |
| equivalent to calling its `handle` method. It illustrates the convenience of using actions as invokable controllers. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-controller.md#_snippet_0 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| $action($someArguments); | |
| // Equivalent to: | |
| $action->handle($someArguments); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Creating a Laravel Action Class (PHP) | |
| DESCRIPTION: This PHP code defines a class `UpdateUserPassword` that utilizes the | |
| `Lorisleiva\Actions\Concerns\AsAction` | |
| trait. This trait transforms a regular class into a Laravel Action, enabling it to be executed as an action within | |
| the | |
| framework. The `handle` method defines the action's core logic. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/installation.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| use Lorisleiva\Actions\Concerns\AsAction; | |
| class UpdateUserPassword | |
| { | |
| use AsAction; | |
| public function handle(User $user, string $newPassword) | |
| { | |
| // ... | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Separating HTML and JSON Responses with Helper Methods in Laravel Actions (PHP) | |
| DESCRIPTION: This example shows an alternative approach to handling different response types in a Laravel Action. By | |
| defining `htmlResponse` and `jsonResponse` helper methods, the `handle` method can focus solely on core logic, while | |
| the | |
| specific response formats are delegated, avoiding conditional `if` statements for cleaner code. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/examples/get-user-profile.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| class GetUserProfile | |
| { | |
| use AsAction; | |
| public function handle(User $user): User | |
| { | |
| return $user; | |
| } | |
| public function htmlResponse(User $user) | |
| { | |
| return view('users.show', compact('user')); | |
| } | |
| public function jsonResponse(User $user) | |
| { | |
| return new UserProfileResource($user); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Using shouldNotRun Helper for Action Mocks in PHP | |
| DESCRIPTION: This example demonstrates the `shouldNotRun()` helper method, used to assert that the action's `handle` | |
| method should not be called during a test. It provides a concise way to express the opposite expectation of | |
| `shouldRun()`, equivalent to `shouldNotReceive('handle')`. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/mock-and-test.md#_snippet_3 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| FetchContactsFromGoogle::shouldNotRun(); | |
| // Equivalent to: | |
| FetchContactsFromGoogle::mock()->shouldNotReceive('handle'); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Injecting Actions as Dependencies in PHP | |
| DESCRIPTION: This example illustrates how an action class can be resolved and utilized through standard dependency | |
| injection within other service classes. It demonstrates constructor injection, where the `UpdateUserPassword` action | |
| is | |
| automatically provided by the container, allowing for clean and testable code. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/basic-usage.md#_snippet_3 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| class MySecurityService | |
| { | |
| protected UpdateUserPassword $updatePassword; | |
| public function __construct(UpdateUserPassword $updatePassword) | |
| { | |
| $this->updatePassword = $updatePassword; | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Default Laravel Action Class Structure (PHP) | |
| DESCRIPTION: This PHP class "MyFirstAction" extends "Lorisleiva\Actions\Action", providing a foundational structure | |
| for | |
| custom actions. It includes default methods like authorize() for permission checks, rules() for data validation, and | |
| handle() for the core business logic, which are essential for defining action behavior. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/installation.md#_snippet_2 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| namespace App\Actions; | |
| use Lorisleiva\Actions\Action; | |
| class MyFirstAction extends Action | |
| { | |
| /** | |
| * Determine if the user is authorized to make this action. | |
| * | |
| * @return bool | |
| */ | |
| public function authorize() | |
| { | |
| return true; | |
| } | |
| /** | |
| * Get the validation rules that apply to the action. | |
| * | |
| * @return array | |
| */ | |
| public function rules() | |
| { | |
| return []; | |
| } | |
| /** | |
| * Execute the action and return a result. | |
| * | |
| * @return mixed | |
| */ | |
| public function handle() | |
| { | |
| // Execute the action. | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Spying on Laravel Actions in PHP | |
| DESCRIPTION: This example demonstrates using `spy()` to create a spy for a Laravel Action, which allows for | |
| assertions | |
| after the action has been executed. It uses `allows()` to define behavior and `shouldHaveReceived()` to verify | |
| method | |
| calls post-execution. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/mock-and-test.md#_snippet_5 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| $spy = FetchContactsFromGoogle::spy(); | |
| $spy->allows('handle')->andReturn(['Loris', 'Will', 'Barney']); | |
| // ... | |
| $spy->shouldHaveReceived('handle')->with(42); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Dispatching Action with Constructor Mapping - PHP | |
| DESCRIPTION: This example illustrates how to dispatch a Laravel Action as a job when the | |
| `getAttributesFromConstructor` | |
| property is defined. This allows attributes to be passed directly as constructor arguments, simplifying the dispatch | |
| call. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/actions-as-jobs.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| // If you have the following constructor mapping. | |
| class PublishANewArticle extends Action | |
| { | |
| protected $getAttributesFromConstructor = ['title', 'body']; | |
| } | |
| // Then you can dispatch the action as a job like this. | |
| PublishANewArticle::dispatch('My blog post', 'Lorem ipsum.'); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Implementing asCommand Method with Interactive Prompts | |
| DESCRIPTION: This snippet demonstrates how to use interactive prompts within the `asCommand` method of a Laravel | |
| Action | |
| to gather user input. It utilizes methods like `ask` and `choice` from the `Command` instance to guide the user, | |
| validate input, and then pass the collected data to the action's `handle` method. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/execute-as-commands.md#_snippet_7 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| class UpdateUserRole | |
| { | |
| use AsAction; | |
| public string $commandSignature = 'users:update-role'; | |
| public function handle(User $user, string $newRole): void | |
| { | |
| $user->update(['role' => $newRole]); | |
| } | |
| public function asCommand(Command $command): void | |
| { | |
| $userId = $command->ask('What is the ID of the user?'); | |
| if (! $user = User::find($userId)) { | |
| return $command->error('This user does not exists.'); | |
| } | |
| $role = $command->choice('What new role should we assign this user?', [ | |
| 'reader', 'author', 'moderator', 'admin', | |
| ]); | |
| $this->handle($user, $role); | |
| $command->info('Done!'); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Prompting Interactive Data in Laravel Action Commands (PHP) | |
| DESCRIPTION: This example demonstrates using the `asCommand` method within a Laravel Action to interactively gather | |
| additional data from the user when the action is run as a console command. It shows how to prompt for input (e.g., | |
| 'What | |
| is the title?') and confirm actions (e.g., 'Publish immediately?'), allowing for dynamic attribute assignment and | |
| conditional execution flow. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/actions-as-commands.md#_snippet_2 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| class PublishANewArticle extends Action | |
| { | |
| protected static $commandSignature = 'make:article'; | |
| public function asCommand(Command $command) | |
| { | |
| $this->title = $command->ask('What is the title?'); | |
| $this->published_at = $command->confirm('Publish immediately?') ? now() : null; | |
| if (! $command->confirm('Are you sure?')) { | |
| throw new Exception('Operation cancelled'); | |
| } | |
| } | |
| // ... | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Chaining Mock Expectations for Laravel Actions in PHP | |
| DESCRIPTION: This example shows how to chain expectations on a mocked Laravel Action. It uses | |
| `shouldReceive('handle')` | |
| to specify the method to mock, `with(42)` to define expected arguments, and `andReturn()` to set the return value. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/mock-and-test.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| FetchContactsFromGoogle::mock() | |
| ->shouldReceive('handle') | |
| ->with(42) | |
| ->andReturn(['Loris', 'Will', 'Barney']); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Customizing Job Dispatch Logic with asJob Method in PHP | |
| DESCRIPTION: This example demonstrates implementing the `asJob` method to customize the action's behavior | |
| specifically | |
| when dispatched as a job. The `handle` method now accepts an additional `fullReport` parameter, and `asJob` calls | |
| `handle` with `true` for `fullReport`, allowing different logic for job-based execution. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/dispatch-jobs.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| class SendTeamReportEmail | |
| { | |
| use AsAction; | |
| public function handle(Team $team, bool $fullReport = false): void | |
| { | |
| // Prepare report and send it to all $team->users. | |
| } | |
| public function asJob(Team $team): void | |
| { | |
| $this->handle($team, true); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Manipulating Action Attributes in PHP | |
| DESCRIPTION: This snippet demonstrates various methods for initializing, filling, retrieving, checking, and setting | |
| attributes on an `Action` instance. It covers common operations like merging new attributes, getting all or specific | |
| attributes, checking for attribute existence, and direct property access for getting and setting values. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/actions-attributes.md#_snippet_0 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| $action = new Action(['key' => 'value']); // Initialise an action with the provided attribute. | |
| $action->fill(['key' => 'value']); // Merge the new attributes with the existing attributes. | |
| $action->all(); // Retrieve all attributes of an action as an array. | |
| $action->only('title', 'body'); // Retrieve only the attributes provided. | |
| $action->except('body'); // Retrieve all attributes excepts the one provided. | |
| $action->has('title'); // Whether the action has the provided attribute. | |
| $action->get('title'); // Get an attribute. | |
| $action->get('title', 'Untitled'); // Get an attribute with default value. | |
| $action->set('title', 'My blog post'); // Set an attribute. | |
| $action->title; // Get an attribute. | |
| $action->title = 'My blog post'; // Set an attribute. | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Defining `getControllerMiddleware` in Laravel Action | |
| DESCRIPTION: This example demonstrates how to define controller-specific middleware directly within the action by | |
| implementing the `getControllerMiddleware` method. It returns an array of middleware names or class names to be | |
| applied | |
| to the action. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-controller.md#_snippet_6 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| public function getControllerMiddleware(): array | |
| { | |
| return ['auth', MyCustomMiddleware::class]; | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Setting Job Connection Property (PHP) | |
| DESCRIPTION: This property defines the specific connection that the `JobDecorator` should use when dispatching the | |
| job. | |
| It provides a straightforward way to assign a connection. Alternatively, this setting can also be configured using | |
| the | |
| `configureJob` method for more complex setups. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-job.md#_snippet_23 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| public string $jobConnection = 'my_connection'; | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Registering Laravel Actions in Routes with Route::actions Macro (PHP) | |
| DESCRIPTION: This example utilizes the Route::actions macro provided by Laravel Actions, which is a convenient | |
| shorthand | |
| for grouping routes under the \App\Actions namespace. It simplifies the registration of actions, making route | |
| definitions cleaner and more concise. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/actions-as-controllers.md#_snippet_4 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| // routes/web.php | |
| Route::actions(function () { | |
| Route::post('articles', 'PublishANewArticle'); | |
| }); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Registering Routes from Laravel Actions | |
| DESCRIPTION: This snippet provides examples of how to register routes defined within actions using the | |
| `Actions::registerRoutes` facade method. It shows how to register routes from default, custom, and multiple | |
| specified | |
| action folders. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-controller.md#_snippet_8 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| use Lorisleiva\Actions\Facades\Actions; | |
| // Register routes from actions in "app/Actions" (default). | |
| Actions::registerRoutes(); | |
| // Register routes from actions in "app/MyCustomActionsFolder". | |
| Actions::registerRoutes('app/MyCustomActionsFolder'); | |
| // Register routes from actions in multiple folders. | |
| Actions::registerRoutes([ | |
| 'app/Authentication', | |
| 'app/Billing', | |
| 'app/TeamManagement', | |
| ]); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Defining `authorize` Method (Response) in Laravel Action | |
| DESCRIPTION: This example illustrates how to define the `authorize` method to return an | |
| `Illuminate\Auth\Access\Response` object. This allows for more granular control over authorization outcomes, | |
| including | |
| providing specific denial messages. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-controller.md#_snippet_11 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| use Illuminate\Auth\Access\Response; | |
| public function authorize(ActionRequest $request): Response | |
| { | |
| if ($request->user()->role !== 'author') { | |
| return Response::deny('You must be an author to create a new article.'); | |
| } | |
| return Response::allow(); | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Registering a Laravel Action as an Event Listener - PHP | |
| DESCRIPTION: This example shows how to register a Laravel Action (`PublishANewArticle`) as an event listener for the | |
| `ProductCreated` event. When the `ProductCreated` event is fired, the action's `handle` method will be invoked, | |
| receiving the event's properties as input. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/basic-usage.md#_snippet_3 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| class ProductCreated | |
| { | |
| public $title; | |
| public $body; | |
| public function __construct($title, $body) | |
| { | |
| $this->title = $title; | |
| $this->body = $body; | |
| } | |
| } | |
| Event::listen(ProductCreated::class, PublishANewArticle::class); | |
| event(new ProductCreated('My new SaaS application', 'Lorem Ipsum.')); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Injecting Dependencies in Constructor - Laravel Actions v2 (PHP) | |
| DESCRIPTION: Demonstrates how to inject dependencies into a Laravel Action's constructor in v2. Actions are resolved | |
| from the container, allowing for standard dependency injection via the __construct method. This example injects | |
| GoogleMapsService. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/upgrade.md#_snippet_5 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| // v2 | |
| class GetDirectionsToRestaurant | |
| { | |
| use AsAction; | |
| protected GoogleMapsService $googleMaps; | |
| public function __construct(GoogleMapsService $googleMaps) | |
| { | |
| $this->googleMaps = $googleMaps; | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Action Attribute Management: get (PHP) | |
| DESCRIPTION: The `get` method retrieves the value of a specific attribute by its key. An optional second argument | |
| can be | |
| provided as a default value, which will be returned if the attribute does not exist. This ensures a fallback value | |
| when | |
| accessing potentially missing attributes. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/with-attributes.md#_snippet_7 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| $action->get('title'); | |
| ``` | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| $action->get('title', 'Untitled'); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Using Gate and User can Method for Authorization - PHP | |
| DESCRIPTION: This example demonstrates using Laravel's `can` method on the authenticated user or the `Gate` facade | |
| within the `authorize` method. This allows for checking specific abilities defined in Laravel, with `Gate::check` | |
| providing support for nullable users. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/add-validation-to-controllers.md#_snippet_3 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| use Illuminate\Support\Facades\Gate; | |
| public function authorize(ActionRequest $request): bool | |
| { | |
| // Using the `can` method. | |
| return $request->user()->can('update', $request->route('article')); | |
| // Using the `Gate` facade (this allows for nullable users). | |
| return Gate::check('update', $request->route('article')); | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Retrieving User Profile with `asController` in Laravel Actions (PHP) | |
| DESCRIPTION: This snippet demonstrates how to define a Laravel Action using the `asController` method to handle user | |
| profile retrieval. It dynamically returns either a JSON resource (`UserProfileResource`) or an HTML view | |
| (`users.show`) | |
| based on whether the request expects JSON, simplifying response handling within a single method. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/examples/get-user-profile.md#_snippet_0 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| class GetUserProfile | |
| { | |
| use AsAction; | |
| public function asController(User $user, Request $request): User | |
| { | |
| if ($request->expectsJson()) { | |
| return new UserProfileResource($user); | |
| } | |
| return view('users.show', compact('user')); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Full Control Over Validator Creation with getValidator - PHP | |
| DESCRIPTION: This example demonstrates implementing the `getValidator` method, which provides full control over the | |
| validator instance that will be generated. Implementing this method will override and ignore any other validation | |
| methods like `rules`, `withValidator`, and `afterValidator`. | |
| SOURCE: | |
| https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/add-validation-to-controllers.md#_snippet_10 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| use Illuminate\Validation\Factory; | |
| use Illuminate\Validation\Validator; | |
| public function getValidator(Factory $factory, ActionRequest $request): Validator | |
| { | |
| return $factory->make($request->only('title', 'body'), [ | |
| 'title' => ['required', 'min:8'], | |
| 'body' => ['required', IsValidMarkdown::class], | |
| ]); | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Adding Validation and Authorization to Action Controllers in PHP | |
| DESCRIPTION: This example demonstrates how to integrate validation and authorization directly into an action class | |
| when | |
| it functions as a controller. By implementing `rules()` and `withValidator()` methods and injecting `ActionRequest`, | |
| the | |
| action can define its own validation rules and custom validation logic, ensuring data integrity before execution. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/basic-usage.md#_snippet_6 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| use Lorisleiva\Actions\Concerns\AsAction; | |
| use Lorisleiva\Actions\ActionRequest; | |
| use Illuminate\Validation\Validator; | |
| class UpdateUserPassword | |
| { | |
| use AsAction; | |
| // ... | |
| public function rules() | |
| { | |
| return [ | |
| 'current_password' => ['required'], | |
| 'password' => ['required', 'confirmed'], | |
| ]; | |
| } | |
| public function withValidator(Validator $validator, ActionRequest $request) | |
| { | |
| $validator->after(function (Validator $validator) use ($request) { | |
| if (! Hash::check($request->get('current_password'), $request->user()->password)) { | |
| $validator->errors()->add('current_password', 'The current password does not match.'); | |
| } | |
| }); | |
| } | |
| public function asController(ActionRequest $request) | |
| { | |
| $this->handle( | |
| $request->user(), | |
| $request->get('password') | |
| ); | |
| return redirect()->back(); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Implementing a Laravel Action with Unified Attributes PHP | |
| DESCRIPTION: Presents a complete example of a `PublishNewArticle` action utilizing the `WithAttributes` trait. It | |
| includes `authorize` and `rules` methods for authorization and validation, and demonstrates handling attributes in | |
| both | |
| `handle` (object) and `asController` (controller) contexts, including using `fillFromRequest`. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/use-unified-attributes.md#_snippet_6 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| class PublishNewArticle | |
| { | |
| use AsAction; | |
| use WithAttributes; | |
| public function authorize() | |
| { | |
| return $this->author->can('publish-new-articles'); | |
| } | |
| public function rules() | |
| { | |
| return [ | |
| 'title' => ['required'], | |
| 'body' => ['required', 'min:100'], | |
| ]; | |
| } | |
| public function handle(User $author, array $attributes = []) | |
| { | |
| $this->set('author', $author)->fill($attributes); | |
| $validatedData = $this->validateAttributes(); | |
| return $this->author->articles()->create($validatedData); | |
| } | |
| public function asController(ActionRequest $request) | |
| { | |
| $this->fillFromRequest($request); | |
| return $this->handle($request->user()); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Running Laravel Actions with Unified Attributes PHP | |
| DESCRIPTION: Provides examples of different ways to run a Laravel Action (`PublishNewArticle`) when using unified | |
| attributes. It shows calling the action with explicit arguments, an array of attributes, or a mixture of both, | |
| demonstrating flexibility in API design. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/use-unified-attributes.md#_snippet_5 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| // As explicit arguments. | |
| PublishNewArticle::run($author, $title, $body); | |
| // As an array of attributes. | |
| PublishNewArticle::run([ | |
| 'author' => $author, | |
| 'title' => $title, | |
| 'body' => $body, | |
| ]); | |
| // As a mixture of both. | |
| PublishNewArticle::run($author, [ | |
| 'title' => $title, | |
| 'body' => $body, | |
| ]); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Registering Routes with Explicit Action Methods (PHP) | |
| DESCRIPTION: This snippet demonstrates how to register Laravel routes where an action's specific method is | |
| explicitly | |
| called for a GET request (e.g., 'showForm'), while the same action handles a POST request as a controller. This | |
| allows | |
| an action to serve multiple endpoints, such as displaying a form and then processing its submission. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/register-as-controller.md#_snippet_8 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| Route::get('/users/{user}/articles/create', [CreateNewArticle::class, 'showForm']); | |
| Route::post('/users/{user}/articles', CreateNewArticle::class); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Instantiating and Running Laravel Actions (PHP) | |
| DESCRIPTION: This snippet illustrates the use of `make` and `run` static helper methods provided by Laravel Actions. | |
| `MyFirstAction::make()` is equivalent to resolving the action from the container, while | |
| `MyFirstAction::run($myArguments)` instantiates the action and immediately calls its `handle` method with the given | |
| arguments. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/one-class-one-task.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| // Equivalent to "app(MyFirstAction::class)".\nMyFirstAction::make();\n\n// Equivalent to | |
| "MyFirstAction::make()->handle($myArguments)".\nMyFirstAction::run($myArguments); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Registering Laravel Action as a Controller Route (PHP) | |
| DESCRIPTION: This snippet illustrates how to register a Laravel Action class directly as a route. By passing the | |
| action | |
| class name to `Route::get`, the action automatically behaves as an invokable controller, simplifying route | |
| definitions | |
| for actions. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/examples/get-user-profile.md#_snippet_2 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| Route::get('users/{user}', GetUserProfile::class); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Setting Custom Exit Code for Laravel Action Commands (PHP) | |
| DESCRIPTION: This example demonstrates how to return a custom exit code from the `consoleOutput` method of a Laravel | |
| Action. By returning an integer value from this method, developers can specify a non-zero exit code, which is useful | |
| for | |
| indicating specific outcomes or errors to the operating system or calling scripts. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/actions-as-commands.md#_snippet_4 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| public function consoleOutput($article, Command $command) | |
| { | |
| return 42; | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Adding Custom Validation Logic with withValidator - PHP | |
| DESCRIPTION: This example demonstrates implementing the `withValidator` method to add custom validation logic, such | |
| as | |
| 'after validation callbacks'. It provides direct access to the `Validator` instance, allowing for advanced | |
| validation | |
| scenarios. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/add-validation-to-controllers.md#_snippet_8 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| use Illuminate\Validation\Validator; | |
| public function withValidator(Validator $validator, ActionRequest $request): void | |
| { | |
| $validator->after(function (Validator $validator) use ($request) { | |
| if (! Hash::check($request->get('current_password'), $request->user()->password)) { | |
| $validator->errors()->add('current_password', 'Wrong password.'); | |
| } | |
| }); | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Customizing Authorization Failure Logic - PHP | |
| DESCRIPTION: This example demonstrates implementing the `getAuthorizationFailure` method to define custom logic for | |
| handling authorization failures. This allows developers to throw specific exceptions or perform other actions when | |
| authorization fails, overriding the default `AuthorizationException`. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/add-validation-to-controllers.md#_snippet_5 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| public function getAuthorizationFailure(): void | |
| { | |
| throw new MyCustomAuthorizationException(); | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Providing Command Help Message with `getCommandHelp` Method | |
| DESCRIPTION: This method provides an extended help message for the Artisan command, displayed when using the | |
| `--help` | |
| option. It offers additional details or usage instructions beyond the basic description. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-command.md#_snippet_5 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| public function getCommandHelp(): string | |
| { | |
| return 'My help message.'; | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Separating JSON and HTML Responses in Laravel Action | |
| DESCRIPTION: This example shows how Laravel Actions provides htmlResponse and jsonResponse helper methods to | |
| automatically handle conditional responses. These methods receive the return value of asController and the Request | |
| object, allowing for clean separation of web page redirects and API resource responses. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/register-as-controller.md#_snippet_5 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| class CreateNewArticle | |
| { | |
| use AsAction; | |
| public function handle(User $user, string $title, string $body): Article | |
| { | |
| return $user->articles()->create(compact('title', 'body')); | |
| } | |
| public function asController(User $user, Request $request): Article | |
| { | |
| return $this->handle($user, $request->get('title'), $request->get('body')); | |
| } | |
| public function htmlResponse(Article $article): Response | |
| { | |
| return redirect()->route('articles.show', [$article]); | |
| } | |
| public function jsonResponse(Article $article): ArticleResource | |
| { | |
| return new ArticleResource($article); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Executing Action using `run` (PHP) | |
| DESCRIPTION: This snippet illustrates how to resolve and immediately execute an action using the static `run` | |
| method. It | |
| also provides the equivalent chain of calling `make()` followed by the `handle()` method. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-object.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| MyAction::run($someArguments); | |
| // Equivalent to: | |
| MyAction::make()->handle($someArguments); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Using shouldRun Helper for Action Mocks in PHP | |
| DESCRIPTION: This snippet illustrates the `shouldRun()` helper method, which provides a more readable alternative to | |
| `shouldReceive('handle')` for setting expectations on the action's primary execution method. It allows chaining | |
| `with()` | |
| and `andReturn()` for argument and return value definitions. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/mock-and-test.md#_snippet_2 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| FetchContactsFromGoogle::shouldRun() | |
| ->with(42) | |
| ->andReturn(['Loris', 'Will', 'Barney']); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Checking if a Laravel Action is Faked in PHP | |
| DESCRIPTION: This example demonstrates the `isFake()` method, which returns a boolean indicating whether a Laravel | |
| Action is currently being mocked or spied upon. It's useful for conditional logic in tests or debugging to determine | |
| the | |
| action's current state. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/mock-and-test.md#_snippet_7 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| FetchContactsFromGoogle::isFake(); // false | |
| FetchContactsFromGoogle::mock(); | |
| FetchContactsFromGoogle::isFake(); // true | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Resolving Dependencies from Action Attributes in Laravel Actions (PHP) | |
| DESCRIPTION: This snippet illustrates how Laravel Actions resolves arguments in the `handle` method directly from | |
| the | |
| action's attributes. It shows examples with and without default values, where missing attributes will return `null` | |
| unless a default is provided. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/dependency-injections.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| // Resolved from the attributes. | |
| // -- $title and $body are equivalent to $action->title and $action->body | |
| // -- When attributes are missing, null will be returned unless a default value is provided. | |
| public function handle($title, $body) {/* ... */} | |
| public function handle($title, $body = 'default') {/* ... */} | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Accessing Validated Data in Handle Method (PHP) | |
| DESCRIPTION: This example shows how to access only the attributes that have successfully passed validation using | |
| `$this->validated()`. This ensures that only clean, validated data is used in the `handle` method, unlike | |
| `$this->all()` | |
| which returns all input attributes. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/validation.md#_snippet_5 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| public function rules() | |
| { | |
| return ['title' => 'min:3']; | |
| } | |
| public function handle() | |
| { | |
| // Will only return attributes that have been validated by the rules above. | |
| $this->validated(); | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Executing Actions as Objects in PHP | |
| DESCRIPTION: This snippet showcases the helper methods `make()` and `run()` provided by the `AsAction` trait for | |
| convenient execution of the action as a standalone object. `make()` resolves the class from the container, while | |
| `run()` | |
| instantiates and immediately executes the `handle` method with provided arguments. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/basic-usage.md#_snippet_2 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| // Equivalent to "app(UpdateUserPassword::class)". | |
| UpdateUserPassword::make(); | |
| // Equivalent to "UpdateUserPassword::make()->handle($user, 'secret')". | |
| UpdateUserPassword::run($user, 'secret'); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Providing Command Help Message with `$commandHelp` Property | |
| DESCRIPTION: This property serves as a declarative alternative to the `getCommandHelp` method for defining an | |
| extended | |
| help message. It provides additional information displayed when the `--help` option is invoked. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-command.md#_snippet_6 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| public string $commandHelp = 'My help message.'; | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Delegating Execution to Sub-Actions in Laravel | |
| DESCRIPTION: This example shows how to use the `delegateTo` method to completely hand off execution to another | |
| Laravel | |
| Action based on conditional logic. The `UpdateProfile` action delegates to `UpdateProfilePicture`, `UpdatePassword`, | |
| or | |
| `UpdateProfileDetails`, ensuring the delegated action runs with the same attributes and type as the parent action. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/nested-actions.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| class UpdateProfile extends Action | |
| { | |
| public function handle() | |
| { | |
| if ($this->has('avatar')) { | |
| return $this->delegateTo(UpdateProfilePicture::class); | |
| } | |
| if ($this->has('password')) { | |
| return $this->delegateTo(UpdatePassword::class); | |
| } | |
| return $this->delegateTo(UpdateProfileDetails::class); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Overriding `__invoke` in Laravel Action | |
| DESCRIPTION: This example demonstrates how to override the default `__invoke` method within a custom action class | |
| while | |
| still satisfying Laravel's requirement for its existence. It uses a trait alias (`invokeFromLaravelActions`) to | |
| preserve | |
| the original `__invoke` functionality from `AsAction`. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-controller.md#_snippet_2 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| class MyAction | |
| { | |
| use AsAction { | |
| __invoke as protected invokeFromLaravelActions; | |
| } | |
| public function __invoke() | |
| { | |
| // ... | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Implementing Unique Jobs with Laravel Actions (PHP) | |
| DESCRIPTION: This example shows how to apply the `ShouldBeUnique` trait to a Laravel Action. It uses the | |
| `$jobUniqueFor` | |
| property to set the uniqueness duration and the `getJobUniqueId` method to dynamically generate the unique | |
| identifier | |
| based on the `Team` object passed as an argument. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/dispatch-jobs.md#_snippet_22 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| use Illuminate\Contracts\Queue\ShouldBeUnique; | |
| class SendTeamReportEmail implements ShouldBeUnique | |
| { | |
| use AsAction; | |
| public int $jobUniqueFor = 3600; | |
| public function getJobUniqueId(Team $team) | |
| { | |
| return $team->id; | |
| } | |
| // ... | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Cherry-Picking Traits for a Custom Action Class in Laravel Actions (PHP) | |
| DESCRIPTION: This example shows how to explicitly include only specific traits, `AsObject` and `AsController`, | |
| directly | |
| within a custom action class (`MyAction`). This "cherry-picking" approach allows developers to select only the | |
| required | |
| functionalities for a particular action, rather than using the full `AsAction` trait. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/granular-traits.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| class MyAction | |
| { | |
| use AsObject; | |
| use AsController; | |
| // ... | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Unified Input/Output Methods - Laravel Actions v1 vs v2 (PHP) | |
| DESCRIPTION: Compares the approach to handling input and output for Laravel Actions between v1 and v2. In v1, | |
| separate | |
| methods like getAttributesFromCommand and consoleOutput were used. In v2, a single method (e.g., asCommand) now | |
| handles | |
| both input parsing, calling the handle method, and managing the output, simplifying the action's interface. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/upgrade.md#_snippet_6 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| // v1 | |
| class CreateNewArticle extends Action | |
| { | |
| public function getAttributesFromCommand(Command $command): array | |
| { | |
| $this->actingAs(User::findOrFail($command->argument('user_id'))); | |
| return [ | |
| 'title' => $command->argument('title'), | |
| 'body' => $command->argument('body'), | |
| ]; | |
| } | |
| public function handle(): Article | |
| { | |
| return $this->user()->articles()->create([ | |
| 'title' => $this->title, | |
| 'body' => $this->body, | |
| ]); | |
| } | |
| public function consoleOutput($article, Command $command): void | |
| { | |
| $command->info("Article \"{$article->title}\" created."); | |
| } | |
| } | |
| ``` | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| // v2 | |
| class CreateNewArticle | |
| { | |
| use AsAction; | |
| public function handle(User $author, string $title, string $body): Article | |
| { | |
| return $author->articles()->create([ | |
| 'title' => $title, | |
| 'body' => $body, | |
| ]); | |
| } | |
| public function asCommand(Command $command): Article | |
| { | |
| $article = $this->handle( | |
| User::findOrFail($command->argument('user_id')), | |
| $command->argument('title')), | |
| $command->argument('body')), | |
| ); | |
| $command->info("Article \"{$article->title}\" created."); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Executing Laravel Action Statically with `run` Method (PHP) | |
| DESCRIPTION: Demonstrates the use of the static `run` method to create and immediately execute a Laravel Action. It | |
| highlights that arguments passed to `run` are forwarded to the constructor, providing a convenient one-liner for | |
| action | |
| execution. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/actions-as-objects.md#_snippet_5 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| // This: | |
| PublishANewArticle::run('My blog post', 'Lorem ipsum.'); | |
| // Is equivalent to this: | |
| $action = new PublishANewArticle('My blog post', 'Lorem ipsum.'); | |
| $action->run(); | |
| ``` | |
| ---------------------------------------- TITLE: Managing Attributes with `WithAttributes` Trait Methods (PHP) | |
| DESCRIPTION: This snippet provides examples of various methods offered by the `WithAttributes` trait for | |
| accessing and updating action attributes. It covers operations like replacing all attributes, merging, filling | |
| from a request, retrieving specific attributes, checking existence, and direct property access. SOURCE: | |
| https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/use-unified-attributes.md#_snippet_2 LANGUAGE: | |
| php CODE: ``` $action->setRawAttributes(['key' => 'value']); // Replace all attributes. | |
| $action->fill(['key' => 'value']); // Merge the given attributes with the existing attributes. | |
| $action->fillFromRequest($request); // Merge the request data and route parameters with the existing attributes. | |
| $action->all(); // Retrieve all attributes. | |
| $action->only('title', 'body'); // Retrieve only the attributes provided. | |
| $action->except('body'); // Retrieve all attributes excepts the one provided. | |
| $action->has('title'); // Whether the action has the provided attribute. | |
| $action->get('title'); // Get an attribute. | |
| $action->get('title', 'Untitled'); // Get an attribute with default value. | |
| $action->set('title', 'My blog post'); // Set an attribute. | |
| $action->title; // Get an attribute. | |
| $action->title = 'My blog post'; // Set an attribute. | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Implementing asCommand Method for Laravel Action | |
| DESCRIPTION: This snippet demonstrates how to make a Laravel Action runnable as a console command. It requires | |
| implementing the `asCommand` method to process command-line arguments and defining the `$commandSignature` and | |
| `$commandDescription` properties. The `asCommand` method receives a `Command` object to interact with the | |
| console, handling user password updates and providing feedback. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/basic-usage.md#_snippet_7 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| class UpdateUserPassword | |
| { | |
| use AsAction; | |
| public string $commandSignature = 'user:update-password {user_id} {password}'; | |
| public string $commandDescription = 'Updates the password a user.'; | |
| public function asCommand(Command $command) | |
| { | |
| $user = User::findOrFail($command->argument('user_id')); | |
| $this->handle($user, $command->argument('password')); | |
| $command->line(sprintf('Password updated for %s.', $user->name)); | |
| } | |
| // ... | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Chaining Actions using Bus Facade in PHP | |
| DESCRIPTION: Demonstrates an alternative way to chain actions using Laravel's `Bus` Facade. This achieves the | |
| same sequential execution as the action-based `withChain` method, providing flexibility in job orchestration. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-job.md#_snippet_9 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| use Illuminate\Support\Facades\Bus; | |
| Bus::chain([ | |
| CreateNewTeamReport::makeJob($team), | |
| OptimizeTeamReport::makeJob($team), | |
| SendTeamReportEmail::makeJob($team), | |
| ])->dispatch(); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Overriding Event Attribute Mapping in PHP | |
| DESCRIPTION: This example shows how to override the default attribute filling behavior for an action listener. | |
| The `getAttributesFromEvent` method is defined within the `PublishANewArticle` action to explicitly map event | |
| data (`$event->product->name`, `$event->product->description`) to specific attributes (`title`, `body`). This | |
| allows for custom attribute extraction from complex event objects. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/actions-as-listeners.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| // Event | |
| class ProductCreated | |
| { | |
| public $product; | |
| } | |
| // Listener | |
| class PublishANewArticle extends Action | |
| { | |
| public function getAttributesFromEvent($event) | |
| { | |
| return [ | |
| 'title' => '[New product] ' . $event->product->name, | |
| 'body' => $event->product->description, | |
| ]; | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Creating a Basic Action Class in PHP | |
| DESCRIPTION: This snippet illustrates the initial structure of a simple PHP class designed to handle a specific | |
| task, such as updating a user's password. It defines the `handle` method, which encapsulates the core logic for | |
| the action, taking necessary parameters like the user object and the new password. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/basic-usage.md#_snippet_0 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| namespace App\Authentication\Actions; | |
| class UpdateUserPassword | |
| { | |
| public function handle(User $user, string $newPassword) | |
| { | |
| $user->password = Hash::make($newPassword); | |
| $user->save(); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Initializing Laravel Action with Positional Arguments (PHP) | |
| DESCRIPTION: Illustrates how to instantiate a Laravel Action using positional arguments in the constructor, | |
| enabled by the custom `getAttributesFromConstructor` method. This simplifies the action's instantiation syntax. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/actions-as-objects.md#_snippet_2 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| $action = new PublishANewArticle('My blog post', 'Lorem ipsum.'); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Configuring Asynchronous Job Settings for ExportUserData in PHP | |
| DESCRIPTION: This snippet illustrates how to define specific job settings, such as connection, queue, | |
| middleware, chain, and delay, directly within the `ExportUserData` action using the `configureJob` method. This | |
| provides fine-grained control over how the dispatched job behaves. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/examples/export-user-data.md#_snippet_3 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| use LorisleivaActionsDecoratorsJobDecorator; | |
| class ExportUserData | |
| { | |
| use AsAction; | |
| public function configureJob(JobDecorator $job): void | |
| { | |
| $job->onConnection('my_connection') | |
| ->onQueue('my_queue') | |
| ->through(['my_middleware']) | |
| ->chain(['my_chain']) | |
| ->delay(60); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Implementing asCommand Method for Laravel Action Command Input | |
| DESCRIPTION: This snippet shows the implementation of the `asCommand` method within a Laravel Action, which is | |
| responsible for parsing command-line arguments and options. It receives an `Illuminate\Console\Command` | |
| instance, allowing access to input and output, and then calls the action's `handle` method with the parsed data. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/execute-as-commands.md#_snippet_6 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| use Illuminate\Console\Command; | |
| class UpdateUserRole | |
| { | |
| use AsAction; | |
| public string $commandSignature = 'users:update-role {user_id} {role}'; | |
| public function handle(User $user, string $newRole): void | |
| { | |
| $user->update(['role' => $newRole]); | |
| } | |
| public function asCommand(Command $command): void | |
| { | |
| $this->handle( | |
| User::findOrFail($command->argument('user_id')), | |
| $command->argument('role') | |
| ); | |
| $command->info('Done!'); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Correct Asynchronous Job Dispatch using Global Helper in PHP | |
| DESCRIPTION: This snippet demonstrates the correct way to dispatch a Laravel Action using the global `dispatch` | |
| helper method. By using `makeJob($team)`, the action is properly instantiated and wrapped as a job, allowing it | |
| to be dispatched to the queue successfully. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/dispatch-jobs.md#_snippet_4 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| // This will work. ✅ | |
| dispatch(SendTeamReportEmail::makeJob($team)); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Configuring JobDecorator Options (PHP) | |
| DESCRIPTION: This method allows direct configuration of the `JobDecorator`'s options within the action. It | |
| provides a fluent interface to set properties like connection, queue, middleware, chain, and delay. This offers | |
| a comprehensive way to customize job dispatch behavior. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-job.md#_snippet_22 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| use Lorisleiva\Actions\Decorators\JobDecorator; | |
| public function configureJob(JobDecorator $job): void | |
| { | |
| $job->onConnection('my_connection') | |
| ->onQueue('my_queue') | |
| ->through(['my_middleware']) | |
| ->chain(['my_chain']) | |
| ->delay(60); | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Creating New Reservation with Code Generation in PHP | |
| DESCRIPTION: This class demonstrates how the `GenerateReservationCode` action is integrated into a larger | |
| workflow, specifically for creating a new reservation. The `handle` method accepts user, concert, and ticket | |
| details, then uses `GenerateReservationCode::run()` to automatically generate and assign a unique code to the | |
| new reservation record before saving it. | |
| SOURCE: | |
| https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/examples/generate-reservation-code.md#_snippet_1 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| class CreateNewReservation | |
| { | |
| use AsAction; | |
| public function handle(User $user, Concert $concert, int $tickets = 1): Reservation | |
| { | |
| return $user->reservations()->create([ | |
| 'concert_id' => $concert->id, | |
| 'price' => $concert->getTicketPrice() * $tickets, | |
| 'code' => GenerateReservationCode::run(), | |
| ]); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Providing Command Description with `$commandDescription` Property | |
| DESCRIPTION: This property offers a declarative way to provide a description for the Artisan command, equivalent | |
| to the `getCommandDescription` method. It defines the command's purpose, updating a user's role. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-command.md#_snippet_4 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| public string $commandDescription = 'Updates the role of a given user.'; | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Chaining Laravel Actions using Bus Facade in PHP | |
| DESCRIPTION: This snippet shows an alternative way to chain multiple Laravel Actions using the `Bus` Facade. It | |
| constructs a chain of jobs, each instantiated with `makeJob`, and then dispatches the entire chain. This method | |
| provides a more direct interaction with Laravel's job bus for complex chaining scenarios. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/dispatch-jobs.md#_snippet_11 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| use Illuminate\Support\Facades\Bus; | |
| Bus::chain([ | |
| CreateNewTeamReport::makeJob($team), | |
| OptimizeTeamReport::makeJob($team), | |
| SendTeamReportEmail::makeJob($team), | |
| ])->dispatch(); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Defining `asCommand` Method for Laravel Actions | |
| DESCRIPTION: This method is invoked when a Laravel Action is executed as an Artisan command. It demonstrates how | |
| to retrieve command arguments and pass them to the action's `handle` method, providing a command-line interface | |
| for the action's core logic. It uses `User::findOrFail` to retrieve the user and `Command::info` for output. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/as-command.md#_snippet_0 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| use Illuminate\Console\Command; | |
| class UpdateUserRole | |
| { | |
| use AsAction; | |
| public string $commandSignature = 'users:update-role {user_id} {role}'; | |
| public function handle(User $user, string $newRole): void | |
| { | |
| $user->update(['role' => $newRole]); | |
| } | |
| public function asCommand(Command $command): void | |
| { | |
| $this->handle( | |
| User::findOrFail($command->argument('user_id')), | |
| $command->argument('role') | |
| ); | |
| $command->info('Done!'); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Implementing asController Method for Action-Based Controllers in PHP | |
| DESCRIPTION: This snippet details the implementation of the `asController` method within an action class, which | |
| is crucial when the action is used as a controller. This method is responsible for extracting data from the | |
| incoming `Request` and mapping it to the arguments expected by the action's `handle` method, then returning a | |
| response. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/basic-usage.md#_snippet_5 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| class UpdateUserPassword | |
| { | |
| use AsAction; | |
| public function handle(User $user, string $newPassword) | |
| { | |
| $user->password = Hash::make($newPassword); | |
| $user->save(); | |
| } | |
| public function asController(Request $request) | |
| { | |
| $this->handle( | |
| $request->user(), | |
| $request->get('password') | |
| ); | |
| return redirect()->back(); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Dispatching ExportUserData Action Synchronously with dispatchNow in PHP | |
| DESCRIPTION: This snippet demonstrates using the `dispatchNow` method to execute the `ExportUserData` action | |
| synchronously. This method processes the action immediately without queuing, making it equivalent to using the | |
| `run` method for direct execution. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/examples/export-user-data.md#_snippet_4 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| ExportUserData::dispatchNow($user); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Defining a Laravel Action with Authorization and Validation - PHP | |
| DESCRIPTION: This snippet defines a `PublishANewArticle` action, including optional `authorize` and `rules` | |
| methods for access control and data validation, respectively. The `handle` method contains the core logic to | |
| create an `Article` using the validated data. The `authorize` method defaults to `true` and `rules` to an empty | |
| array if not defined. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/basic-usage.md#_snippet_0 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| // app/Actions/PublishANewArticle.php | |
| class PublishANewArticle extends Action | |
| { | |
| public function authorize() | |
| { | |
| return $this->user()->hasRole('author'); | |
| } | |
| public function rules() | |
| { | |
| return [ | |
| 'title' => 'required', | |
| 'body' => 'required|min:10', | |
| ]; | |
| } | |
| public function handle() | |
| { | |
| return Article::create($this->validated()); | |
| } | |
| } | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Initializing Laravel Action with Array Attributes (PHP) | |
| DESCRIPTION: Demonstrates the default way to initialize a Laravel Action by passing an associative array of | |
| attributes to its constructor. This method allows for clear assignment of values to action properties. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/1.x/actions-as-objects.md#_snippet_0 | |
| LANGUAGE: PHP | |
| CODE: | |
| ``` | |
| $action = new PublishANewArticle([ | |
| 'title' => 'My blog post', | |
| 'body' => 'Lorem ipsum.', | |
| ]); | |
| ``` | |
| ---------------------------------------- | |
| TITLE: Registering Action as Event Listener using Event Facade (PHP) | |
| DESCRIPTION: This snippet shows how to register an action as an event listener using the `Event::listen` facade | |
| method. It supports both class-based events (`MyEvent::class`) and string-based events (`'my_string_events.*'`), | |
| providing flexibility for event registration outside of the `EventServiceProvider`. | |
| SOURCE: https://github.com/lorisleiva/laravel-actions-docs/blob/main/2.x/listen-for-events.md#_snippet_1 | |
| LANGUAGE: php | |
| CODE: | |
| ``` | |
| Event::listen(MyEvent::class, MyAction::class); | |
| // Note that it also works with string events. | |
| Event::listen('my_string_events.*', MyAction::class); | |
| ``` | |
| </laravel-actions-code-snippets> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace [namespace]; | |
| use App\Actions\Property\ListMyPropertiesAction; | |
| use App\Http\Requests\Store[class]Request; | |
| use Livewire\Attributes\Computed; | |
| use Livewire\Attributes\Layout; | |
| use Livewire\Component; | |
| #[Layout('components.layouts.theme')] | |
| class [class] extends Component | |
| { | |
| public ?string $title = '[class]'; | |
| // LiveWire Mount Method | |
| public function mount(): void | |
| { | |
| } | |
| // LiveWire Validation Rules (for update/create) | |
| protected function rules(): array | |
| { | |
| $request = new Store[class]Request; | |
| return $request->rules(); | |
| } | |
| // LiveWire Computed Properties | |
| #[Computed] | |
| public function properties() | |
| { | |
| return ListMyPropertiesAction::run(Auth::user())->properties; | |
| } | |
| // Render blade view | |
| public function render() | |
| { | |
| return view('[view]'); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment