Laravel Restful Actions
We often use controllers for list some products, add product, update product or Delete product. Now we are dig into for make easy understand the flow. For all this actions you can categorize the 7 Restful actions.
php artisan help make:controller
Controller options
Let use one of the options to make all 7 Restful actions. Create new controller for Products
php artisan make:controller PostsController -r -m Posts
In this statement you used -r -> resources and -m -> model. It will create PostsController and Posts Model files
<?php
namespace App\Http\Controllers;
use App\Models\Posts;
use Illuminate\Http\Request;
class PostsController 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 \App\Models\Posts $posts
* @return \Illuminate\Http\Response
*/
public function show(Posts $posts)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Posts $posts
* @return \Illuminate\Http\Response
*/
public function edit(Posts $posts)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Posts $posts
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Posts $posts)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Posts $posts
* @return \Illuminate\Http\Response
*/
public function destroy(Posts $posts)
{
//
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Posts extends Model
{
use HasFactory;
}
Posts.php
Here you covered all Restful actions for Product, to add, show, edit or delete. If you are not run the command you can write all these 7 Restful actions manually.
However, you have to mention all this actions at routes and correspond actions with HTTP verbs like GET, POST, PUT and DELETE.
Ex:
GET Products (List of products)
GET Products/:id (Single Product)
PUT Products/:id (For product update)
POST Products (Create a Product)
Delete Products/:id (Delete a product)
Comments
Post a Comment
Thank you :)