Forms and Validation

CSRF in Forms

CSRF attacks trick authenticated users into performing unwanted actions on a trusted site. For example, if your Laravel app has a /user/email route that accepts POST requests to change an email, an attacker could create a fake form that submits their own email instead. Laravel provides built-in protection to prevent such exploits.


Form

in HTML
<h1>Register</h1>
<form action="/to/action" methode="post" >
@csrf
<input type="text" name="firstname" />
<input type="radio" name="gender" value="men" />
<input type="checkbox" name="gender" value="men" />
<select name="city">
<option value="1"> Vienna </option>
</select>
<input type="submit" />
</form>
in Controller
public function action(Request $request)
{
return $request->input();
}
public function action(Request $request)
{
return view('display', ["request" => $request]);
}

CSRF (Cross-Site Request Forgeries)

When using POST, PUT, PATCH, or DELETE in Laravel forms, include a hidden CSRF token so Laravel can validate the request. Use @csrf in Blade templates to add this token automatically.

<form>
@csrf
...
<input type="hidden" name="_token" value=" {{csrf_token}}" />
</form>
public function action(Request $request)
{
$token = $request-> session()->token();
return $token;
}

Validation

Laravel offers multiple ways to validate incoming data, with the validate method being the most common. It provides various validation rules, including checking if a value is unique in a database table.

Validation Logic

some validation examples for different data types
$validated = $request->validate([

'email' => 'required|email|unique:users,email_address',
'username' => 'required|alpha_num',
'price' => 'decimal:2',
'amount' => 'numeric|min:1',
'start_date' => 'required|date',
'end_date' => 'required|date|after_or_equal:start_date',

]);

Displaying the Validation Errors

@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li> {{ $error }} </li>
@endforeach </ul>
</div>
@endif

The @error Directive

The @error Blade directive checks if a validation error exists for a specific field. Inside it, you can echo $message to display the error message.

<input id="title"
type="text"
name="title"
class=" @error('title') is-invalid @enderror">

@error('title')
<div class="alert alert-danger"> {{ $message }} </div>
@enderror

Laravel's global old helper retrieves previous input values in Blade templates, making form repopulation easier. If no old input exists, it returns null.

<input type="text" name="title" value="{{ old('title') }}" >