Generate laravel api via command line in laravel 5.1

 

In this article you wil learn how to Generate laravel api via command line in laravel 5.1 . for this we will use a laravel package called laravel5-api-generator . this package Generates boilerplate for laravel REST API: migration, controller, model, request and route.  all credits goes to package author Artur Śmiarowski so lets get started with installation

Installation

composer require --dev asmiarowski/laravel5-api-generator

Add this to appProvidersAppServiceProvider inside boot() method:

if ($this->app->environment() == 'local') {
    $this->app->register('SmiarowskiGeneratorsGeneratorsServiceProvider');
}

For POST / PUT data to work you either have to send your request with Accept: application/json header or set up json responses globally in app/Http/Requests/Request.php like so:

/**
 * Overwrite Laravel Request method because API is always returning json
 * @return bool
 */
public function wantsJson()
{
    return true;
}

Command syntax

php artisan make:api-resource <table_name> --schema="<column_name>:<column_type>(<arguments>):<option>(<arguments>); [...]" --softdeletes

Command options

–schema – required, schema of your migration, validators will be set based on fields and types specified.

–softdeletes – optional, add softDeletes() to migration

Column types

http://laravel.com/docs/5.1/migrations#creating-columns

Custom types

– email – puts string type column in your migration and email validation for your request

Column options

foreign, index, unique, default, nullable, first, after, unsigned

Example command

php artisan make:api-resource emails --schema="email:email:unique; title:string; body:text; status:integer:default(1); user_id:integer:foreign(users)" --softdeletes

Creates:

app/Http/Controllers/EmailController.php

app/Htpp/Requests/EmailRequest.php

app/Email.php

database/migrations/*timestamp*_create_emails_table.php

And appends resource routes to app/routes.php with pattern for id of the resource.

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Get The best In Web dev

Get The best In Web dev

Join dunebook and recieve best in Angular, React, Vue, Python, Java & more. Directly to your inbox once a week FREE !

You have Successfully Subscribed!

Pin It on Pinterest