Laravel's Artisan is a powerful command-line interface (CLI) included with Laravel. It provides a number of helpful commands that can assist you while you build your application.
Goals of the Tutorial:
In this tutorial, we will learn how to use the Artisan CLI for Laravel. We will explore various Artisan commands and understand how to use them to streamline our Laravel development process.
Learning Outcomes:
By the end of this tutorial, you will be able to:
Prerequisites:
Artisan CLI is driven by the powerful Symfony Console component. The php artisan list command will list all available Artisan commands:
php artisan list
You can get more information about any command in the list by using the help command:
php artisan help migrate
You can create your own Artisan commands using the make:command command. This will create a new command class in the app/Console/Commands directory.
php artisan make:command YourCommandName
Laravel allows you to schedule Artisan commands to run at specified intervals.
// Inside App\Console\Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('inspire')->hourly();
}
tinker commandThe tinker command allows you to interact with your entire Laravel application from the command line.
php artisan tinker
After running this command, you can interact with your application as if you're in a Laravel session.
>>> $user = App\Models\User::first();
>>> echo $user->name;
Let's create a new command named SendEmails.
php artisan make:command SendEmails
This command will create a new SendEmails class within your app/Console/Commands directory.
In this tutorial, we have learned about Laravel's Artisan CLI - how to use built-in commands, create new commands, and schedule commands to run at specified intervals.
Exercise 1: Try using the tinker command to retrieve all users from your database.
Exercise 2: Create a new Artisan command named ClearCache that clears your application's cache.
Exercise 3: Schedule your ClearCache command to run once every day.
Solutions:
php artisan tinker and then App\Models\User::all();.php artisan make:command ClearCache, then implement the handle method to call Artisan::call('cache:clear');.App\Console\Kernel.php, add $schedule->command('clear:cache')->daily(); to the schedule method.Keep practicing and exploring different Artisan commands to increase your productivity when developing Laravel applications.