Artisan: Your Command-Line Companion
Artisan is Laravel's CLI tool that automates repetitive development tasks. Mastering Artisan commands will dramatically speed up your workflow.
Essential Artisan Commands
# Generate code
php artisan make:model Post -mfc # Model + Migration + Factory + Controller
php artisan make:controller Api/PostController --api
php artisan make:middleware EnsureAdmin
php artisan make:request StorePostRequest
# Database
php artisan migrate # Run pending migrations
php artisan migrate:rollback # Undo last batch
php artisan migrate:fresh --seed # Drop all, re-migrate, seed
php artisan db:seed # Run database seeders
# Development
php artisan serve # Start dev server
php artisan tinker # Interactive REPL
php artisan route:list # Show all routes
php artisan optimize:clear # Clear all caches
Tinker: Interactive PHP Shell
Tinker lets you interact with your application in real-time:
php artisan tinker
>>> $user = User::factory()->create(['name' => 'John']);
>>> $user->posts()->count();
>>> Post::where('published', true)->latest()->first();
>>> Cache::flush();
Creating Custom Commands
php artisan make:command SendWeeklyNewsletter
class SendWeeklyNewsletter extends Command
{
protected $signature = 'newsletter:send
{--test : Send only to test subscribers}';
protected $description = 'Send the weekly newsletter to all subscribers';
public function handle(): int
{
$subscribers = $this->option('test')
? Subscriber::where('is_test', true)->get()
: Subscriber::active()->get();
$bar = $this->output->createProgressBar($subscribers->count());
foreach ($subscribers as $subscriber) {
Mail::to($subscriber)->queue(new WeeklyNewsletter());
$bar->advance();
}
$bar->finish();
$this->newLine();
$this->info("Sent to {$subscribers->count()} subscribers.");
return Command::SUCCESS;
}
}
Schedule it in routes/console.php:
Schedule::command('newsletter:send')->weeklyOn(1, '8:00');
Artisan turns hours of manual work into seconds of automated commands.