亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Define the Route
Create and Handle the Form
Process Submission in Controller
Handle Validation Errors and Feedback
Home PHP Framework Laravel How to handle form submissions in Laravel?

How to handle form submissions in Laravel?

Oct 15, 2025 am 03:55 AM

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.

How to handle form submissions in Laravel?

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to log messages to a file in Laravel? How to log messages to a file in Laravel? Sep 21, 2025 am 06:04 AM

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

How to authenticate an API in Laravel How to authenticate an API in Laravel Sep 18, 2025 am 12:26 AM

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

How to use the hasManyThrough relationship in Laravel? How to use the hasManyThrough relationship in Laravel? Sep 17, 2025 am 06:38 AM

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

How to write a feature test in Laravel with Pest? How to write a feature test in Laravel with Pest? Sep 16, 2025 am 06:12 AM

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

How to create a full-text search in Laravel? How to create a full-text search in Laravel? Sep 16, 2025 am 03:42 AM

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

How to implement API authentication with Laravel Sanctum? How to implement API authentication with Laravel Sanctum? Sep 19, 2025 am 04:08 AM

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

How to use route resource controllers in Laravel? How to use route resource controllers in Laravel? Sep 24, 2025 am 05:05 AM

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.

How to redirect a user in a Laravel controller? How to redirect a user in a Laravel controller? Sep 21, 2025 am 05:26 AM

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.

See all articles