Laravel Forms


How do you create a form in Laravel?

In Laravel, you can create forms using standard HTML form elements or Blade form helpers provided by the laravelcollective/html package (optional). A typical form will use the <form> HTML tag with method and action attributes.

Example of a basic form:

<form method="POST" action="/submit-form">
    <input type="text" name="name" placeholder="Enter your name" />
    <input type="email" name="email" placeholder="Enter your email" />
    <button type="submit">Submit</button>
</form>

In this example, a form is created with POST as the method and submits data to the /submit-form route.


How do you handle form submissions in Laravel?

To handle form submissions in Laravel, you define a route that captures the form data and a controller method that processes the request. The form data is accessible through Laravel’s request object using the request() helper or the injected Request instance.

Example of handling a form submission:

use Illuminate\Http\Request;

Route::post('/submit-form', function (Request $request) {
    $name = $request->input('name');
    $email = $request->input('email');
    
    // Process the data, save to the database, etc.
});

In this example, the form data is captured using the $request object and can be processed accordingly.


How do you protect forms from CSRF attacks in Laravel?

Laravel automatically protects forms from Cross-Site Request Forgery (CSRF) attacks by requiring a CSRF token on every form that performs a state-changing action (e.g., POST, PUT, DELETE). You can include the CSRF token in your forms using the @csrf Blade directive.

Example of including a CSRF token in a form:

<form method="POST" action="/submit-form">
    @csrf
    <input type="text" name="name" placeholder="Enter your name" />
    <input type="email" name="email" placeholder="Enter your email" />
    <button type="submit">Submit</button>
</form>

In this example, the @csrf directive generates a hidden input containing the CSRF token, ensuring the form is secure.


How do you validate form data in Laravel?

Laravel provides a built-in validation mechanism to validate incoming form data. You can validate the form data by using the validate() method in the controller or request handler.

Example of validating form data:

use Illuminate\Http\Request;

Route::post('/submit-form', function (Request $request) {
    $validatedData = $request->validate([
        'name' => 'required|max:255',
        'email' => 'required|email',
    ]);
    
    // If validation passes, process the data
});

In this example, the validate() method checks that the name field is required and has a maximum length of 255 characters, while the email field must be a valid email address.


How do you display validation errors in a form?

If validation fails, Laravel automatically redirects the user back to the previous page with error messages. You can display these error messages in your Blade view using the $errors variable.

Example of displaying validation errors:

<form method="POST" action="/submit-form">
    @csrf
    <input type="text" name="name" placeholder="Enter your name" />
    @if ($errors->has('name'))
        <div>{{ $errors->first('name') }}</div>
    @endif
    
    <input type="email" name="email" placeholder="Enter your email" />
    @if ($errors->has('email'))
        <div>{{ $errors->first('email') }}</div>
    @endif
    
    <button type="submit">Submit</button>
</form>

In this example, validation error messages are displayed next to the corresponding input fields if validation fails.


How do you retain old input after validation failure?

When form validation fails, Laravel automatically flashes the old input data to the session, allowing you to retain the user's input. You can display the old input in your form fields using the old() helper.

Example of retaining old input:

<form method="POST" action="/submit-form">
    @csrf
    <input type="text" name="name" value="{{ old('name') }}" placeholder="Enter your name" />
    <input type="email" name="email" value="{{ old('email') }}" placeholder="Enter your email" />
    <button type="submit">Submit</button>
</form>

In this example, the old() helper repopulates the form fields with the previously submitted data in case of validation failure.


How do you handle file uploads in Laravel forms?

To handle file uploads, you need to set the enctype attribute of the form to multipart/form-data. In your controller, you can retrieve the uploaded file using the $request->file() method and store it using the store() method.

Example of handling a file upload:

<form method="POST" action="/upload-file" enctype="multipart/form-data">
    @csrf
    <input type="file" name="file" />
    <button type="submit">Upload</button>
</form>

In the controller:

use Illuminate\Http\Request;

Route::post('/upload-file', function (Request $request) {
    $file = $request->file('file');
    $path = $file->store('uploads');
    
    // Process the uploaded file, save the path to the database, etc.
});

In this example, a file is uploaded via the form, and Laravel stores it in the uploads directory.


How do you handle PUT and DELETE form methods in Laravel?

HTML forms only support GET and POST methods. To send PUT or DELETE requests in Laravel, you need to include a hidden input field with the method you want to use. You can use the @method directive in Blade to handle this.

Example of using the PUT method in a form:

<form method="POST" action="/update/1">
    @csrf
    @method('PUT')
    <input type="text" name="name" placeholder="Enter new name" />
    <button type="submit">Update</button>
</form>

In this example, the form sends a PUT request to update a resource, even though the method is set to POST in the form's attributes.


How do you redirect back with input in Laravel?

To redirect back to the previous page with the input data (so users don't have to re-enter the form), you can use the withInput() method along with a redirect.

Example of redirecting back with input:

return redirect()->back()->withInput();

This will redirect the user back to the previous page and retain the form input values.


How do you access the request instance globally in Laravel?

Laravel automatically injects the Request object into your routes and controllers, allowing you to access form data and other request-related information. However, if you need access to the request object globally, you can use the request() helper function.

Example of accessing the request object globally:

$name = request('name'); // Retrieve the 'name' input field

In this example, the request() helper retrieves the value of the name input field from the form submission.

Ads