Tutorial: https://www.youtube.com/watch?v=4pc6cgisbKE
Docs: https://laravel.com/docs/master/seeding#writing-seeders
Objective: Generates dummy data (30 articles)
php artisan make:factory ArticleFactory
php artisan make:seeder ArticlesTableSeeder
php artisan make:model Article
php artisan make:migration create_articles_table --create=articles
php artisan migrate
php artisan db:seed
php artisan make:controller ArticleController --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
];
}
}