First, define GET and POST routes for form display and submission. Then, create a Blade form with @csrf for security. Next, handle the request in a controller using validation rules. Finally, display success messages or validation errors in the template using Laravel’s built-in session and error handling.
Handling form submissions in Laravel is straightforward thanks to its built-in features for routing, validation, and request handling. Here’s how you can do it effectively.
Define the Route
Laravel uses routes to direct HTTP requests to the appropriate controller or closure. For form handling, you typically need a GET route to display the form and a POST route to process the submission.
- Use
Route::get()
for showing the form. - Use
Route::post()
for handling the form data.
Example:
Route::get('/contact', [ContactController::class, 'showForm']); Route::post('/contact', [ContactController::class, 'handleSubmit']);
Create and Handle the Form
In your Blade template, use Laravel's Blade directives like @csrf
to include a CSRF token, which protects against cross-site request forgery.
Example form:
<form method="POST" action="/contact"> @csrf <input type="text" name="name" /> <input type="email" name="email" /> <button type="submit">Send</button> </form>
Process Submission in Controller
In your controller, receive the incoming request and validate the data before processing.
- Inject
Illuminate\Http\Request
to access form input. - Use the
validate()
method to ensure data meets rules.
Example:
public function handleSubmit(Request $request) { $validated = $request->validate([ 'name' => 'required|string|max:100', 'email' => 'required|email', ]); // Process the data (e.g., save to database, send email) return redirect()->back()->with('success', 'Form submitted!'); }
Handle Validation Errors and Feedback
If validation fails, Laravel automatically redirects back with errors. In your Blade template, check for these errors and display them.
Example in Blade:
@if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @if (session('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif
Basically just route, validate, process, and respond. Laravel handles the heavy lifting so you don’t have to worry about raw POST data or CSRF protection manually.
The above is the detailed content of How to handle form submissions in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

LaravelusesMonologtologmessagesviatheLogfacade,withdefaultlogsstoredinstorage/logs/laravel.log.Configurechannelsinconfig/logging.phptocontroloutput;thedefaultstackchannelaggregatesmultiplehandlerslikesingle,whichwritestoafile.UseLog::info(),Log::warn

InstallLaravelSanctumviaComposerandpublishitsfiles,thenrunmigrations.2.AddtheHasApiTokenstraittotheUsermodel.3.Definelogin,logout,anduserroutesinapi.php,usingSanctum’sauth:sanctummiddleware.4.ProtectAPIroutesbyapplyingtheauth:sanctummiddleware.5.Incl

ACountrycanaccessallPoststhroughUsersusinghasManyThrough.Forexample,withcountries,users,andpoststableslinkedbyforeignkeys,theCountrymodeldefinesahasManyThroughrelationshiptoPostviaUser,enablingefficientindirectdataretrievalacrosstwoone-to-manyrelatio

InstallPestviaComposerandinitializeitinLaraveltosetuptesting.2.Createafeaturetestintests/Featuretovalidateuser-facinginteractionslikeHTTPrequestsanddatabasechangesusingPest’s簡潔syntax.

Toimplementfull-textsearchinLaravel,firstaddafull-textindexinthemigrationusing$table->fullText(['title','content']);thenusewhereFullText(['title','content'],$query)inqueriesforefficientsearching;encapsulatelogicinamodelscopeforreusabilityandfallba

ToimplementAPIauthenticationwithLaravelSanctum,youneedtosetuptoken-basedauthenticationthatallowsSPAs,mobileapps,andthird-partyservicestosecurelyaccessyourAPI.SanctumprovidesalightweightapproachbyissuingAPItokensthatcan

Laravel resource controller quickly processes CRUD operations through RESTful routing, uses the Artisan command to generate controllers and register resource routes, and can create all standard routes in a single line of code, which supports restriction of actions, adding middleware and naming, and combines routing model binding to automatically parse parameters, improve development efficiency and keep the code structure clear.

Use the redirect() helper function to realize redirection in the Laravel controller, such as redirect()->route('home') to jump to the named route, redirect('/dashboard') to the specified URL, redirect()->back() returns to the previous page, and use withInput() to retain form data and with() to pass session messages. It is recommended to use named routes to improve maintainability.
