Image Validation in Laravel

10-Mar-2023

.

Admin

Image Validation in Laravel

Hi Dev,

In this blog, I will show you image validation in laravel. The file under validation must be an image like jpeg, png, bmp, gif, svg, or webp.

You can easily validate images in Laravel like file max size and lots of new validation option as image dimension for image upload.

The file validation in file size to validate the file in laravel. In case of string, it validates the length in characters.we have a new validation option: image dimensions for image uploads. The validation rule is called dimensions.

Here is a solution and i also give you full example with route and view file too. Let's see bellow solution :

Solution


public function solution(Request $request)

{

$request->validate([

'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000',

]);

}

Route: routes/web.php

Route::get('image','FrontHomeController@image');

Route::post('image-store','FrontHomeController@imageStore')->name('image.store');

Controller : app/Http/controllers/FrontHomeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FrontHomeController extends Controller

{

public function image()

{

return view('image');

}

public function imageStore(Request $request)

{

$request->validate([

'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000',

]);

return redirect()->back();

}

}

View : resources/views/image.blade.php

<!DOCTYPE html>

<html>

<head>

<title>image validation in laravel - nicesnippets.com</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha256-L/W5Wfqfa0sdBNIKN9cG6QA5F2qx4qICmU2VgLruv9Y=" crossorigin="anonymous" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha256-WqU1JavFxSAMcLP2WIOI+GB2zWmShMI82mTpLDcqFUg=" crossorigin="anonymous"></script>

</head>

<body>

<div class="container">

<div class="row">

<div class="col-md-6 offset-3">

<div class="card mt-5">

<div class="card-header bg-success">

<h3 class="text-white text-center"><strong>Image Validation in Laravel</strong></h3>

</div>

<div class="card-body">

@if(count($errors) > 0)

@foreach($errors->all() as $error)

<div class="alert alert-danger">{{ $error }}</div>

@endforeach

@endif

<form action="{{ route('image.store') }}" method="post" enctype="multipart/form-data">

@csrf

<div class="form-group">

<label><b>Image :-</b></label>

<input type="file" name="image" class="form-control" value="{{ old('image') }}">

</div>

<div class="form-group text-center">

<button class="btn btn-success" type="submit">Save</button>

</div>

</form>

</div>

</div>

</div>

</div>

</div>

</body>

</html>

It will help you...

#Laravel 7

#Laravel

#Laravel 6