Open Laboratory for Technocrats

Grab the developer role, learn concepts & prepare with senior software engineers to get solutions for problems in a software job. Coding and Programming Solutions crafted for you.

Laravel - Run Controller in Terminal

How to run a controller function via command line or terminal in Laravel?


Well, there are several ways to do it. Like making a command shell which will use the code to get in contact with the controller and then play around it.

Above method sounds good and for a long term goal, it should be implemented. The things which we will need to take care with this will be that input taken from the terminal should be properly taken and then return should be the same.

If you need to do this once only then you might be not wondering to write that whole bunch of code if it's just 10 lines yes we developers are too lazy to even write a single line of code.

In this scenario, Laravel 5 gives a good tool so far that I have used is "tinker".


This is going to be super easy with simple and effective use cases.

Let see now how to play around tinker.
  • Go to the Project folder
  • Run command
    • $ php artisan tinker
  • Now we are at the shell prompt of tinker
  • Next, we need to get the script call for our controller
  • Run this command under tinker shell - Assuming controller name as MyController
    • $ $controller = app()->make('App\Http\Controllers\MyController');
  • Now as code is self-explanatory we have initiated the controller to object, next we will call the function
  • The function call can be done as:
    • $ app()->call([$controller, 'myMethodName'], []);
This function call and Enter will execute the function.

How to pass the arguments?
  • $ app()->call([$controller, 'myMethodName'], [user_id=>123]);
That's so simple and easy, but this is good if you are testing something. Make a proper command shell if its a long term task for the team.

Please let us know about the article in comments if there is anything that we can improve or should consider about growing let us know.



Top #3 Articles