Submit Form Data in Laravel 9 | use of @csrf token | use controllers | use {{url('/')}}

Submit Form Data in Laravel

1. create a form blade file in views directory - views>form.blade.php

2. copy paste bootstrap starter template in the blade file.

3. create a form using bootstrap or code mannually.

example are given below -

<div class="container">
        <h1 class="text-center">Registration Form</h1>
        <form action="{{url('/')}}/register" method="post">
            @csrf
            <div class="mb-3">
              <label class="form-label">Name</label>
              <input aria-describedby="emailHelpId" class="form-control" id="name" name="name" type="text" />
            </div>
            <div class="mb-3">
              <label class="form-label">Name</label>
              <input aria-describedby="emailHelpId" class="form-control" id="email" name="email" placeholder="abc@mail.com" type="email" />
            </div>
            <div class="mb-3">
              <label class="form-label">Name</label>
              <input aria-describedby="emailHelpId" class="form-control" id="password" name="password" type="password" />
            </div>
            <button class="btn btn-primary">Submit</button>
        </form>
    </div>

4. {{url('/')}}/register is use to get base url and when url hits /register the form will be appear on web page.

5. @csrf is a token. without @csrf token form will not submit that's why it is mandatory.

6. Now open new terminal in vs code or do it mannually. and create controller file

using this command -

php artisan make:controller registrationController

7. Open Routes>web.php and give the controller path -

use App\Http\Controllers\registrationController;

and when /register hits send it to the index function inside controller - 

Route::get('/register', [registrationController::class, 'index']);

8. Go to App>Http>Controllers>registrationController and create a public function-

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class registrationController extends Controller
{
    public function index(){
        return view('form');
    }
}

9. If you want to get data you have submitted then Again go to Routes>web.php and write post funtion.

Note- above function was get and this is post.

Route::post('/register', [registrationController::class, 'register']);

10. Now again go to registrationController file and write on more function -

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class registrationController extends Controller
{
    public function index(){
        return view('form');
    }

    public function register(Request $request){
        echo '<pre>';
        print_r($request-&gt;all());
    }
}
</pre>

Now you can try http://127.0.0.1:8000/register on brower if you have started your localhost. if not started then - follow these steps.

Submit your form and get the data you have submitted.

Comments