How to Create a Laravel CSS-Minify Command

In this article you’ll learn how to use Laravel’s Artisan command line tool, and how to create a customized command. Note that you need to be familiar with the Laravel framework to get the most of this article.

What are we building

In this tutorial we’re going to build a command to minify our css assets, which will be used like this:

--concat: (optional) concatenate the minified files into one file called all.min.css.

What is a Laravel Command

Artisan is the name of the command line utility in Laravel. It comes with a set of predefined commands, which you can list with php artisan list. If you want to show the help for a specific command, you can use php artisan help command.

Creating the Css Minifier Command

To create an artisan command, you can use the command:make command. This command accepts one argument:

name: the class name for the command.

and three options:

--command: the name that should be typed to run the command.

--path: by default the commands are stored within the app/commands folder, however, you can change that with this option.

--namespace: you can use this option to namespace your set of commands, e.g. in the command command:make, the make command is under the command namespace.

Now, to create our command we will use php artisan command:make CssMinCommand --command=cssminwhich will create a CssMinCommand.php file within our app/commands directory.

Note: when using the IS_ARRAY argument it should be the last one on the returned arguments array. (obviously).

Options

Our cssmin command will only have two options. To define an option we pass an array:

array('name','shortcut','mode','description','defaultValue')

name: the name of your option (ex: comments).

shortcut: a shorter version of your option (ex: --verbose and -v).

mode: can be one of the four options (InputOption::VALUE_IS_ARRAY, InputOption::VALUE_OPTIONAL, InputOption::VALUE_REQUIRED, InputOption::VALUE_NONE), the first three values are similar to the arguments.

VALUE_NONE: indicates that the option is a boolean flag ( ex: --verbose ).

You can try the command with multiple files or uncomment the sleep function line to see a live effect.

Note: This version will be tagged as v3 on the final repository.

Conclusion

In this article we’ve learned how create and extend Laravel commands. Laravel has a lot of built-in commands that you can explore, and you can also check our final repository on GitHub to test the final result. Questions? Comments? Would you like to see more Artisan Command tutorials? Let us know!

Younes is a freelance web developer, technical writer and a blogger from Morocco. He's worked with JAVA, J2EE, JavaScript, etc., but his language of choice is PHP. You can learn more about him on his website.