RPeraltaJr
1/9/2020 - 10:18 PM

Factory and Seeding (For Creating an API)

Create a Factory

php artisan make:factory ArticleFactory

Create a Seeder

php artisan make:seeder ArticlesTableSeeder

Create a Model

php artisan make:model Article

Create a Migration and Migrate

php artisan make:migration create_articles_table --create=articles
php artisan migrate

Run the Seed

php artisan db:seed

Create a Resource Controller

php artisan make:controller ArticleController --resource

Create a Resource

php artisan make:resource Article

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use Faker\Generator as Faker;

$factory->define(App\Article::class, function (Faker $faker) {
    return [
        'title' => $faker->text(50),
        'body'  => $faker->text(200)
    ];
});
<?php

use Illuminate\Database\Seeder;

class ArticlesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Article::class, 30)->create();
    }
}
<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

// List articles
Route::get('articles', 'ArticleController@index');

// List single article
Route::get('article/{id}', 'ArticleController@show');

// Create new article
Route::post('article', 'ArticleController@store');

// Update article
Route::put('article', 'ArticleController@store');

// Delete article
Route::delete('article/{id}', 'ArticleController@destroy');
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Article extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        // return parent::toArray($request);

        // List out the only fields you need
        return [
            'id'    => $this->id,
            'title' => $this->title,
            'body'  => $this->body
        ];
    }
}