Favorit

Breaking News

Laravel Tutorial - Submiting Form


Laravel - With the form in place, we are ready to handle the POST data and validate data. Back in the routes/web.php file, create another route for the POST request:

use Illuminate\Http\Request;

Route::post('/submit', function (Request $request) {
    $data = $request->validate([
        'title' => 'required|max:255',
        'url' => 'required|url|max:255',
        'description' => 'required|max:255',
    ]);

    $link = tap(new App\Link($data))->save();

    return redirect('/');
});
This route is a little more complicated than the others.

First, we are injecting the Illuminate\Http\Request object, which holds the POST data and other data about the request.

Next, we use the request’s validate() method to validate the form data. The validate method was introduced in Laravel 5.5 and is a nice shortcut over other methods used for validation. As a bonus, the validated fields are returned to the $data variable, and we can use them to populate our model.

We require all three fields, and using the pipe character; we can define multiple rules. All three rules can have a max of 255 characters, and the url field requires a valid URL.

If validation fails, an exception is thrown, and the route returns the user with the original input data and validation errors.

Next, we use the tap() helper function to create a new Link model instance and then save it. Using tap allows us to call save() and still return the model instance after the save.

Typically, you would have to do the following without tap, it just adds a little syntactic sugar:

$link = new \App\Link($data);
$link->save();

return $link;
If we want to populate a new model with data, we need to allow the fields to be “fillable” via mass assignment. The fillable property is designed to prevent fields from being mass-assigned except for the items you define in the array.

In our case, we are validating each field so allowing them to be mass-assigned is safe. To allow our model to assign values to these fields, open the app/Link.php file and update it to look like the following:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Link extends Model
{
    protected $fillable = [
        'title',
        'url',
        'description'
    ];
}
If we wanted to prevent mass-assignment, this is how our code would look:

$data = $request->validate([
    'title' => 'required|max:255',
    'url' => 'required|url|max:255',
    'description' => 'required|max:255',
]);

$link = new \App\Link;
$link->title = $data['title'];
$link->url = $data['url'];
$link->description = $data['description'];

// Save the model
$link->save();
The last thing we do in our POST route redirects the user back to the home page after saving the link successfully.

No comments