Using resource is one of the good way of making restful api end points in laravel. We can easily make a set of routes and associated functionality on controller with naming conventions as well.
We start with resource controller. Let’s take an example of an article.
Now, we can create ArticlesController using following artisan command.
php artisan make:controller ArticlesController --resource
Now, just look at the controller inside app/Http/Controllers/ directory you will see following methods in ArticlesController,
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
}
}
When we use resource option while creating controller then all restful methods are created. We can add all necessary codes to make the above methods working as per our requirements.
Also Read: Custom helper function in laravel
Now, we can create routes for each of these controller methods by adding following line to web.php
Route::resource('articles','ArticlesController');
Above code will register all restful routes to the ArticlesController. We can list out the articles routes using artisan command like this,
php artisan route:list
Registered routes are:
GET | HEAD articles articles.index App\Http\Controllers\ArticlesController@index
POST articles articles.store App\Http\Controllers\ArticlesController@store
GET | HEAD articles/create articles.create App\Http\Controllers\ArticlesController@create
GET | HEAD articles/{article} articles.show App\Http\Controllers\ArticlesController@show
PUT | PATCH articles/{articles} articles.update App\Http\Controllers\ArticlesController@update
DELETE articles/{articles} articles.destroy App\Http\Controllers\ArticlesController@destroy
GET | HEAD articles/{articles}/edit articles.edit App\Http\Controllers\ArticlesController@edit
In this way, we can create resource controller with restful methods so that we can register routes to those methods accordingly.
Leave your Feedback