Laravel API Resources Artisan Command
Published on by Paul Redmond
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:
php artisan resources:create PostChecking if the model exists ...The model Post does not exist. Should I create it? (yes/no) [yes]: > Should I create the migration for Post? (yes/no) [yes]: > Should I create the factory for Post? (yes/no) [yes]: > Should I create the seeder for Post? (yes/no) [yes]: > Creating 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:
/*|--------------------------------------------------------------------------| Post endpoints|-------------------------------------------------------------------------- */Route::name('posts.')->prefix('posts')->group(function () { Route::get('/', 'PostControllerAPI@index')->name('index'); Route::post('/', 'PostControllerAPI@store')->name('create'); Route::get('/{post}', 'PostControllerAPI@show')->name('show'); Route::patch('/{post}', 'PostControllerAPI@update')->name('update'); Route::delete('/{post}', 'PostControllerAPI@destroy')->name('destroy');});
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.