In Laravel, HTTP request verbs are used to define the type of action being requested from the server. These verbs correspond to the different operations you might want to perform on a resource, such as retrieving data, submitting data, updating data, or deleting data. Laravel provides a clean and intuitive way to handle these HTTP verbs through its routing system.
A GET request is used to retrieve data from the server. In Laravel, you can define a route that responds to a GET request using the Route::get
method.
Route::get('/users', [UserController::class, 'index']);
A POST request is used to send data to the server, typically to create a new resource. In Laravel, you can define a route that responds to a POST request using the Route::post
method.
Route::post('/users', [UserController::class, 'store']);
A PUT request is used to update an existing resource. In Laravel, you can define a route that responds to a PUT request using the Route::put
method.
Route::put('/users/{id}', [UserController::class, 'update']);
A PATCH request is similar to a PUT request but is used for partial updates to an existing resource. In Laravel, you can define a route that responds to a PATCH request using the Route::patch
method.
Route::patch('/users/{id}', [UserController::class, 'updatePartial']);
A DELETE request is used to delete a resource from the server. In Laravel, you can define a route that responds to a DELETE request using the Route::delete
method.
Route::delete('/users/{id}', [UserController::class, 'destroy']);
Here’s how you might implement these methods in a controller:
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
// Handle GET request to retrieve all users
return User::all();
}
public function store(Request $request)
{
// Handle POST request to create a new user
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
]);
return User::create($validated);
}
public function update(Request $request, $id)
{
// Handle PUT request to update an existing user
$user = User::findOrFail($id);
$user->update($request->all());
return $user;
}
public function updatePartial(Request $request, $id)
{
// Handle PATCH request to partially update an existing user
$user = User::findOrFail($id);
$user->update($request->only(['name', 'email']));
return $user;
}
public function destroy($id)
{
// Handle DELETE request to delete a user
$user = User::findOrFail($id);
$user->delete();
return response()->json(['message' => 'User deleted successfully']);
}
}
Published By: Krishanu Jadiya
Updated at: 2024-08-17 14:49:59