Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
File Validation in laravel 8

How to use file validation in Laravel 8 with example

Aman Jain, November 27, 2021January 26, 2022

Laravel provides multiple ways to validate a form or a file in form with it’s own validation library. In this tutorial we will learn about the image validation for specific extension and file size.

In this tutorial i will use a simple form and a file input field to validate the file from laravel validation library. we will use mainly two validators one is Mime and other is max. Mime validator is used to validate the mime type of file and max is used to validate the file size

We will use four Laravel rules to validate the image here

  1. Mimes (Use to check the type of file)
  2. Max (Used to validate the file size)

So, it can be use in any controller or route as below

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{

 function validateImage($request Request){
   $validator = Validator::make($request->all(), [
            'file' => ['required','mimes:pdf,docx','max:2048'],
        ]); 

}
}

Here, we used Validator library and it’s validation rules.

 $validator = Validator::make($request->all(), [
             'file' => ['required','mimes:pdf,docx','max:2048'],
        ]); 

Let’s learn with simple example

Step 1 : Create a controller

Create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller PostController

Now, add use Illuminate\Support\Facades\Validator; and methods

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{

    
    public function create()
    {
        return view('post.create');
    }

    public function store(Request $request, Response $response)
    {
        $validator = Validator::make($request->all(), [
            'file' => ['required','mimes:pdf,docx','max:2048']
           // file validation
            
        ]); // create the validations
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {
            
            return back()->withInput()->withErrors($validator);
            // validation failed redirect back to form

        }
        else
        {
            //handle the form 
        }  
    }
   
}

Here, we added file validation using mimes.

Step 2 : Create Routes

Second step is to create the routes to show the form and submit the form

<?php

use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\PostController;


Route::get('/create-post',[PostController::class, 'create']);
Route::post('/submit-post',[PostController::class, 'store']);

Step 3 : Create the view for form

We have created routes and controller and now we need to create the form so we are creating the view file for it.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Readerstacks laravel 8 image validation</title>
 <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
   </head>
    <body class="antialiased">
    <div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-6 offset-md-3">
            <h3>Laravel 8 file validation - Readerstacks</h3>
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <form method="post" action="{{url('submit-post')}}" name="registerform">
             <div class="form-group">
                <label>Image</label>
                <input type="file" name="file"  class="form-control" />
                @csrf
              </div>
               
            
              <div class="form-group">
                <button class="btn btn-primary">Post</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <!-- credits -->
    <div class="text-center">
      <p>
        <a href="#" target="_top">Laravel 8 file validation </a>
      </p>
      <p>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
      </p>
    </div>
  </div>
    </body>
</html>

Check the screenshot for output:

Screenshot 2021 11 27 at 1.12.33 PM
File validation laravel

Also Read : Image validation with example in Laravel 8

Related

Php Laravel imagelaravelphpvalidation

Post navigation

Previous post
Next post

Related Posts

Laravel How to use Post Ajax Request in Laravel 8 9

How to use Post Ajax Request in Laravel 8 / 9?

June 2, 2022June 2, 2022

Post Ajax request in laravel is use to communicate with server without reloading the page. Ajax requests are useful when we do not want to refresh the page and update the content of page so in that case Ajax request are very useful. Sometimes its also useful while submitting a…

Read More
Php How to Get Last Record With Group By in Laravel Eloquent

How to Get Last Record With Group By in Laravel Eloquent ?

September 7, 2022March 16, 2024

In this tutorial we will learn to get last record with group by in laravel eloquent. while working with group by in mysql its gives first record from the group by records that means if you have multiple record with same id and you want the most recent record or…

Read More
Php How to create seeders in laravel

How to create seeders in laravel 9 with example ?

February 19, 2022February 22, 2022

As the name implies seeders, seeder are used to fill the database using seed classes. Sometimes in our application we wanted to test our application with some data and in that case we require seed the database may be with dummy data. Using the seeder we can create n number…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version