Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Resource Routes - RESTful Routes in Laravel

Laravel, PHP
David Egan

Laravel allows you to quickly and easily set up controllers and routes so that you can interact with data in a RESTful way..

Create a Model and Database Table

Create a Model in the usual way (the -m flag creates a migration for the model, allowing you to set up a new database table):

php artisan make:model Article -m

Amend the migration as necessary and run php artisan migrate to set up the new table.

Create a Resourceful Controller

Create a controller using Artisan using the --resource option:

php artisan make:controller ArticleController --resource

This creates a new controller under app/Http/Controllers, with stubbed out methods to allow interaction with the database table for this resource:

  • index(): Display a listing view for the resource
  • create(): Show the form for creating a new resource
  • store(): Store a newly created resource in storage
  • show(): Display the specified resource
  • edit(): Update the specified resource in storage
  • destroy(): Remove the specified resource from storage

Ruby on Rails has avery similar command: rails g scaffold_controller Article - which stubs out a similar controller.

Create Route for the Resource

In your routes/web.php file (Laravel 5.3), create a new route using the resource() method:

Route::resource('articles', 'ArticleController');

If you check the registered routes now using php artisan route:list, you’ll see the new (named) routes automatically set up:

| Domain | Method    | URI                     | Name             | Action                                         | Middleware   |

|        | GET|HEAD  | articles                | articles.index   | App\Http\Controllers\ArticleController@index   | web          |
|        | POST      | articles                |   | App\Http\Controllers\ArticleController@store   | web          |
|        | GET|HEAD  | articles/create         | articles.create  | App\Http\Controllers\ArticleController@create  | web          |

|        | GET|HEAD  | articles/{article}      |    | App\Http\Controllers\ArticleController@show    | web          |
|        | PUT|PATCH | articles/{article}      | articles.update  | App\Http\Controllers\ArticleController@update  | web          |
|        | DELETE    | articles/{article}      | articles.destroy | App\Http\Controllers\ArticleController@destroy | web          |
|        | GET|HEAD  | articles/{article}/edit | articles.edit    | App\Http\Controllers\ArticleController@edit    | web          |

The resource has been set up so that the correct controller methods are triggered when you access a specified route with a given HTTP verb.

comments powered by Disqus