Laravel API Resources Artisan Command

News

February 14th, 2020

api-computer-laravelnews-featured.png

The Laravel Resources package is an artisan command for speeding up the development of APIs by creating the boilerplate code around a default API structure:

You interface with this package via the resources:create command, which will generate all the files you’ll need to build an API resource:

1php artisan resources:create Post
2Checking if the model exists ...
3The model Post does not exist.
4
5 Should I create it? (yes/no) [yes]:
6 >
7 Should I create the migration for Post? (yes/no) [yes]:
8 >
9 Should I create the factory for Post? (yes/no) [yes]:
10 >
11 Should I create the seeder for Post? (yes/no) [yes]:
12 >
13
14Creating 6 resources ...

The command will create the following files for you:

  • Controller
  • Form request
  • Resource and resource collection
  • Policy
  • Model
  • Database factory
  • Database migration
  • Database seeder
  • Routes

Here’s the format of the routes added to the routes/api.php file:

1/*
2|--------------------------------------------------------------------------
3| Post endpoints
4|--------------------------------------------------------------------------
5 */
6Route::name('posts.')->prefix('posts')->group(function () {
7 Route::get('/', 'PostControllerAPI@index')->name('index');
8 Route::post('/', 'PostControllerAPI@store')->name('create');
9 Route::get('/{post}', 'PostControllerAPI@show')->name('show');
10 Route::patch('/{post}', 'PostControllerAPI@update')->name('update');
11 Route::delete('/{post}', 'PostControllerAPI@destroy')->name('destroy');
12});

The package has a customizable configuration which affects things like file location(s), filename prefix and suffixes. You can learn more about this package by checking out the code and readme on GitHub: LaravelResources.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.