Getting Form Input Value in Laravel

Used:

Laravel 5.8

Before Started:

  • You should have knowledge about basic Route, read here
  • You should have knowledge about Controller, read here

Known:

I want to make a form that sending employee name like image below:

When i press Send button then the name will be displayed like right image

Question :
How to do that … ?

Answer:
We require 3 steps to do, namely:

  • Create View
  • Create Controller
  • Add Route

Create View

Create employee_resign.blade.php in resources/views folder and insert this code:

<form action = "/employee/resign" method = "post">
@csrf
Employee Name :<input name="empName"  />
<input type="submit" value="Send">
</form>

Explain:

  • action = “/employee/resign”, this is a route
  • @csrf is used to protect from cross-site request forgery
  • @csrf must be included in form

Create Employee Controller

Create Employee.php filename inside app/Http/Controllers folder and add this code below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class Employee extends Controller
{
        function resign(Request $request){
		echo $request->input('empName');
		
	}
}

Explain:

$request->input(’empName’) is used to get an attribute name from form input with name=”empName”

Add Route

Open the routes/web.php and add this code:

Route::get("resign", function(){
	return view('employee_resign');
});
Route::post('employee/resign', 'Employee@resign');

Explain:

  • Route::get(“resign”) , this code means that if i open “http://localhost:8000/resign” then resources/views/employee_resign.blade.php executed
  • Route::post(’employee/resign’, ‘Employee@resign’), this code means that if i open “http://localhost:8000/employee/resign” in browser URL then resign function inside Employee Controller will be Executed

Result:

Open “http://localhost:8000/resign” in your browser and see the result


Thanks for reading

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *