A simple laravel task trigger

v1.2.2 2021-07-01 08:10 UTC

This package is auto-updated.

Last update: 2021-10-01 00:11:48 UTC


Laravel Task

GitHub Workflow Status Packagist Packagist Packagist

🇪🇸 Documentación en español aqui

Table of content:


Install via composer

# PHP >= 8
composer require victor-falcon/laravel-task
# Previous PHP versions
composer require victor-falcon/laravel-task:1.1.4


1. Basic usage

Create a simple task using:

artisan task:make Shop/CreateUserShop

You can pass Shop/CreateUserShop to create the class in a sub-folder or just the task name. The default path is app/Tasks.



namespace App\Tasks\Shop;

use VictorFalcon\LaravelTask\Task;
use VictorFalcon\LaravelTask\Taskable;

final class CreateUserShop implements Task
	use Taskable;

	private User $user;

	public function __construct(User $user)
		$this->user = $user;

	public function handle(ShopCreator $creator): Shop
		// Create your shop

and trigger it:

$shop = CreateUserShop::trigger($user);

2. With validation

If you want, you can pass validated data to your tasks using the Laravel validator. For example, If you need to validate a user creation you can do something like this.

final class CreateUser implements Task
	public function rules(): array
		return [
			'name' => 'required|string|min:5',
			'email' => 'required|email|unique:users,email',

	public function handle(): User
		return User::create($this->data);

And then you can trigger your task with extra data using:

	'name' => 'Víctor Falcón',
	'email' => '',

You can customize the messages with the method messages(): array in your task or add custom attributes with customAttributes(): array.

If you want to customize the errors bag name of the validator just define the string $errorBag property in your class.

3. With authorization

Sometimes you need to check if the user triggering the task is authorized or not. You can do that by adding a simple authorize(): bool method to your task. If this method returns false an AuthorizationException will thrown on before execution.

public function authorize(): bool
	return $this->user()->can('create', Product::class);

In any task you can access to the current logged user with $this->user() or, if you want, you can pass a user object by doing:


4. Recover response

By default, each task is executed without returning any value. So if you want to recover the result of a task you must call the result() method.

// This will return the result of the `handle` method inside our task
$product = CreateProduct::trigger()->withValid($data)->result();

Generate IDE Help

In order to make more easy to write and use your task you can generate a _ide_helper_tasks.php file automatically with the artisan task:ide-help command.

Update config

If you want, you can publish the package config to customize, for example, where do you want you task to be store at:

artisan vendor:publish --tag=laravel-task