Skip to content

Basic CRUD

JP Barbosa edited this page Mar 11, 2016 · 3 revisions

Basic CRUD

Generate model and migration for articles
php artisan make:model Article --migration
Add custom fields to migration up
nano database/migrations/*create_articles_table.php
    ...
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });
    }
    ...
Migrate database
php artisan migrate
Add list of fields that can be mass assign
nano app/Article.php
class Article extends Model
{
    protected $fillable = ['title', 'content'];
}
Create article using console
php artisan tinker
App\Article::create(['title' => 'Article Title', 'content' => 'Article Content']);
Generate articles controller
php artisan make:controller ArticlesController
Add basic RESTfull methods for articles controller
nano app/Http/Controllers/ArticlesController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Article;

class ArticlesController extends Controller
{

    public function index()
    {
        return Article::all();
    }

    public function store(Request $request)
    {
        return Article::create($request->all());
    }

    public function show(Article $article)
    {
        return $article;
    }

    public function update(Request $request, Article $article)
    {
        $article->update($request->all());
        return $article;
    }

    public function destroy(Article $article)
    {
        return (string) $article->delete();
    }

}
Add routes for articles
nano app/Http/routes.php
Route::singularResourceParameters();
...
Route::resource('articles', 'ArticlesController');
Start the server
php artisan serve
Create article using cURL
curl -H "Accept: application/json" \
     http://localhost:8000/articles \
     --data "title=Article Title" \
     --data "content=Article Content"
{"title":"Article Title","content":"Article Content"...}
List articles and check if the new record was created
curl -H "Accept: application/json" http://localhost:8000/articles
Show specific article
curl -H "Accept: application/json" http://localhost:8000/articles/1
Update an article
curl -X PATCH \
     -H "Accept: application/json" \
     --data "title=Edited Article Title" \
     http://localhost:8000/articles/1
Remove article using cURL
curl -X DELETE \
     -H "Accept: application/json" \
     http://localhost:8000/articles/1
Add basic CRUD to Git
git add .
git commit -m "Add articles basic CRUD"
Next step: Validation
Clone this wiki locally