Skip to content

Make a complete REST API instead of CRUD

MisterDebug edited this page Oct 26, 2022 · 1 revision

You need to generate a REST API ? You're in the right place 🙂

Usage

Create a REST API

Let's make a real life example : Build an API for posts

A Post can have a title and a content fields

CRUD generator command :

php artisan make:rest-api nameOfYourCrud "column1:type, column2" (theory)

php artisan make:rest-api post "title:string, content:text" (for our example)

Migration

A migration file is created in your database/migrations directory. If necessary edit it and run :

php artisan migrate

Controller

A controller file is created in your app/Http/Controllers/API directory. All methods (index, store, show, update, destroy) are filled with your fields.

Routes

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)

Resource

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,
        ];
    }
}

Request

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.

Screenshots

Try our API now, try to POST data :

image

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 :

image

All these routes are available :

image

Enjoy your new REST API 🎉

Remove a 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

image