Laravel Model for Web Forms


one of the most important things you will do when developing website is creating form. while creating form in HTML is very simple, how can you retrieve the submitted data. this tutorial shows you exactly how to do it.

if you followed my previous tutorial, we created our routes and controllers, we are going to be using the same /users route and controller.

Add Routing


the first step is to open the routes/web.php file and add the following two lines at the end of the file:
Route::get('users/create', ['uses' => 'UsersController@create']);
Route::post('users', ['uses' => 'UsersController@store']);


open file UsersController.php and add the following public function
public function store(Request $request){
return $request->all();

}

Add function


UsersController.php should look like this:
{
public function index(){
$string = 'Hello, This is the users route';
return view('users.index', compact('string'));
}
public function create(){
return view('users.create');
}
public function store(Request $request){
return $request->all();
}
}

Create Html


create a new blade file in resources/views/users/create.blade.php and add this code:
<form method="post" action="/users">
{!! csrf_field() !!}
name<input type="text" name="name"><br>
email<input type="email" name="email"><br>
password<input type="password" name="password"><br>
<input type="submit" value="Create">
</form>


database


out goal is to save the submitted data into a database, in order to have access to our database, (I will be using MySQL) you will need to open the .env file and change the variable values according to your database: database table, database user, database password:
DB_DATABASE=laravel5
DB_USERNAME=root
DB_PASSWORD=Very_h@rd_p@55w0rd


save the changes to the .env file and restart the server: (php artisan serve)

Database Migrate


you will need to create the users table using laravel migration, all you need is a simple command:
php artisan migrate

using phpmyadmin, you can confirm a new users table has been created, the command output will look like this:
Migration table created successfully.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table


View in Browser


now open your browser http://localhost:8000/users/create
you should see something like this:
25-p4605-simple-html-form.jpg


after you sumit the form, you will get the results you submitted in json format:
{"_token":"G2qvJN8X6ioSoNrGJwpWK6Dq8ym0XzJANiJb9Zuw","name":"Fernando","email":"[email protected]","password":"mypassword"}

if you prefer, here is a video