-
Notifications
You must be signed in to change notification settings - Fork 44
Make a complete REST API instead of CRUD
You need to generate a REST API ? You're in the right place 🙂
Let's make a real life example : Build an API for posts
A Post
can have a title
and a content
fields
php artisan make:rest-api nameOfYourCrud "column1:type, column2"
(theory)
php artisan make:rest-api post "title:string, content:text"
(for our example)
A migration file is created in your database/migrations directory. If necessary edit it and run :
php artisan migrate
A controller file is created in your app/Http/Controllers/API directory. All methods (index, store, show, update, destroy) are filled with your fields.
To create your routes for this new controller, you can do this :
Route::apiResource("posts", PostsController::class);
(don't forget to import your PostsController
in your api.php
file)
A resource file is created in your app/Http/Resources directory. By default, only fields asked is displayed, you can edit it according to your needs.
class PostResource extends JsonResource
{
public function toArray($request)
{
return
[
'title' => $this->title,
'content' => $this->content,
];
}
}
A request file is created in your app/Http/Requests directory. By default, all fields are required, you can edit it according to your needs.
Try our API now, try to POST data :
You can't POST without a title and a content. To modify this behavior, you can change rules in your request file.
If you want change the return of the validation array, you can edit failedValidation
method in this file
By default :
public function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
'success' => false,
'message' => 'Validation errors',
'data' => $validator->errors()
]));
}
Now if you POST with a title and a content, a post is created :
All these routes are available :
Enjoy your new REST API 🎉
You can delete all files (except migrations) created by the make:rest-api
command at any time (you don't need to remove all files by hand)
php artisan rm:rest-api nameOfYourCrud --force
php artisan rm:rest-api post --force
(in our example)
--force (optional) can delete all files without confirmation