• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Artisan Commands You're Not Using (But Definitely Should)

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
If you’ve worked with Laravel, you’ve typed php artisan serve
and maybe even php artisan migrate. And while those are useful, they barely scratch the surface of what Artisan can do.

Artisan isn’t just a tool for running migrations or spinning up servers—it’s a command-line companion that can boost your productivity, simplify debugging, and teach you more about Laravel’s inner workings. Yet many developers (my past self included) tend to stick with the same 3-4 commands and miss out on some seriously powerful features.

Whether you’re just starting with Laravel or you’ve been building apps for years, it’s worth revisiting Artisan with fresh eyes. In this post, I’m diving into some of the lesser-known, underrated, or just plain useful Artisan commands I think every Laravel developer should explore.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Route Commands with Artisan


php artisan route:list --method=POST

What it does:
Filters the route list to only show routes that respond to the POST method.

Use case:
You're debugging a form submission or an API endpoint and only want to see POST routes instead of searching through every GET, PUT, or DELETE one.

php artisan route:list --path=admin

What it does:
Only shows routes that contain the word "admin" in the URI.

Use case:
If you're working on an admin panel and want to quickly audit only the /admin/... routes.

php artisan route:list --only-vendor

What it does:
Lists only the routes that come from vendor packages (like Laravel Breeze, Jetstream, Filament, etc.).

Use case:
You want to see what routes are registered by packages you're using—especially useful when customizing or debugging third-party tools.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Essential make: Commands You Should Be Using More Often


php artisan make:controller PostController --model=Post --requests --test

--model=Post
Automatically binds the model to your resource controller — no need to type-hint manually.

--requests
Generates StorePostRequest and UpdatePostRequest classes with validation ready to go.

--test, --pest, --phpunit
Choose your test style. This creates a matching test class for the controller you're generating.

--invokable
Creates a one-method controller – perfect for single-action classes like WebhookController.

--singleton
If you're working with singleton resources (like "profile"), this flag changes the routing logic to match.

php artisan make:model Post --all

--all
Generates the model, migration, factory, seeder, policy, resource controller, and form requests. Insane time saver.

--controller
Generates a controller along with the model (you can pair it with --resource or --api too).

--factory, --seeder, --migration
Generate any of these pieces individually if you don’t need the full --all.

--morph-pivot, --pivot
Generate intermediate or polymorphic pivot tables with special behavior built in.

--policy
If you’re using Laravel’s authorization system, this gives you a head start.

php artisan make:migration create_posts_table --create=posts

--create=table_name
Tell Laravel to scaffold a full Schema::create(...) block for the specified table.

--table=existing_table
Use this to update an existing table – Laravel will scaffold Schema::table(...).

--path=custom/migrations
Store your migration in a custom directory — helpful for organizing modular codebases.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Time-Saving Shortcut Flags


Many make: commands support shorthand versions of common flags. Instead of typing each one out, you can speed things up with single-character options.

php artisan make:model Product -mcfs

This one-liner does a ton of work for you by generating:

-m: a migration file
-c: a controller
-f: a factory
-s: a seeder

It’s your go-to for starting a new model with CRUD scaffolding ready. You can even pair it with --resource if you want a fully RESTful controller.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Build Your Own Artisan Commands


Sometimes the built-in Artisan commands aren't enough. You can create your own commands to automate repetitive tasks, run data cleanup, trigger services, or just make your workflow smoother.

You can generate a new command with:

php artisan make:command CleanOldPosts

This creates a file in app/Console/Commands/CleanOldPosts.php. Open it, and you’ll see something like this:


protected $signature = 'posts:clean';

protected $description = 'Deletes posts older than 90 days.';

You can define the logic inside the handle() method:


public function handle()
{
Post::where('created_at', '<', now()->subDays(90))->delete();
$this->info('Old posts cleaned up!');
}

Once your command is registered, you can run it just like any other Artisan command:

php artisan posts:clean

You can make it so it runs on schedule. Add it to your app/Console/Kernel.php:

$schedule->command('posts:clean')->daily();

Boom — automated.

Creating your own Artisan commands is perfect for:

  • data cleanup (e.g. old users, expired coupons)
  • sending reminders or reports
  • batch processing
  • integrating with APIs on a schedule
  • seeding logic-heavy demo data


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Wrapping Up


Don’t let your workflow be limited by muscle memory and just a few familiar commands. Take time to explore what’s possible. Automate the boring stuff. Tweak the defaults. Build your own tools. That’s where you grow from just using the framework to mastering it.

If you learned something new, consider bookmarking this guide — and if you’ve got favorite Artisan tricks (and let’s be honest, there are tons) I didn’t mention, I’d love to hear them in the comments!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу