Ad
Ad
Ad
Tag

File Upload

Browsing

Today, We are going to create the Laravel File Upload tutorial. Almost, The application has a file upload functionality. Laravel provides an easy interface for File Uploading. So, Today we are going to learn Laravel File Upload Tutorial. We can easily handle file upload by a user. We focus only on the File Upload code in this tutorial. If you are beginners and want to learn File Uploading step by step then Just follow this tutorial.

Laravel File Upload Tutorial

First of all, We are going to create the Form with the Browse/File input element. Let’s open your view file and create the browse button with form like.

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

<form action="{{ route('uploadfile.post') }}" method="POST" enctype="multipart/form-data">
    @csrf

	<div class="form-group">
	    <label for="imageupload">Image</label>
	    <input type="file" name="image" class="form-control-file">
	    <small id="emailHelp" class="form-text text-muted">Select Image file Jpeg, jpg, Png</small>
	</div>

	<button type="submit" class="btn btn-primary">Submit</button>

</form>

Finally, We are ready for the file uploading. Now we need to validate the uploaded file by user and store that image into the directory. So, Let’s open the controller file for uploading and validating image file.

$request->validate([
    'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);

$imageName = time().'.'.request()->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $imageName);

return redirect()->back()
    ->with('success','Image uploaded successfully.')
    ->with('image',$imageName);

As per the above code, First, we validate the file like

  • Selected file must be an image file
  • The File size must be less than 2MB
  • The File type must be JPEG, JPG, PNG

We checked the basic validation file If you want to add more restriction for Image uploading you can write your own validation rules.

The uploaded by a user are stored in the public/images directory. You can easily access the uploaded file from the images folder like.

<img src="{{ asset('images/'.$imageName) }}">

Just replace the $imageName with image name then check the image are visible in a browser or not.

If you face any issue with the file uploading write the comment below.

Today, We are going to learn Laravel File upload step by step. Almost, the file upload functionality exists on every application. Laravel provides an easy interface for uploading a file. Every application has file upload functionality on user profile page. So, We can easily create the file upload functionality for Laravel application. This tutorial is created only for the Laravel Beginners users. Let’s see the File upload tutorial step by step.

First of all, We are going to install Laravel by following composer command

composer create-project --prefer-dist laravel/laravel laravelhive

If you face any issue with Laravel installation just follow this tutorial for Laravel installation.

Laravel File Upload

After, installing Laravel We are going to create the migration file by the following command

php artisan make:migration create_blog_table

The Migration file is generated into “database/migrations” folder. Open the migration file and create table columns like below.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBlogTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blog', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blog');
    }
}

Finally, We are ready with the migration file. Now, let’s create the table by follow migration command

php artisan migrate

If you face any issue something like “1071 specified key was too long max key length is 767 bytes” then just follow this tutorial to resolve this issue. Then again follow the migrate command.

Finally, We are ready with the blog table. We use blog table for storing images data.

Laravel Model

Now, let’s we are going to the creating migration file for the Blog table by the following command.

php artisan make:model Blog

The Model file is generated into App Folder. Just open it and write the code like.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    protected $table = "blog";
    protected $fillable = ['title','image'];
}

Finally, We are ready with Laravel Eloquent Model. Now, Let’s we are going for the creating the Laravel Routes. Let’s open the routes/web.php  file and write the route like.

Route::get('/laravelhive/blogs',['as' => 'blogs', 'uses' => 'BlogController@index']);
Route::get('/laravelhive/uploadfile',['as' => 'uploadfile', 'uses' => 'BlogController@blogForm']);
Route::post('/laravelhive/uploadfile',['as' => 'uploadfile.post', 'uses' => 'BlogController@uploadFile']);

Finally, We are ready with the route for File upload tutorial. Now, let’s we are going for the BlogController.

Laravel Controller

Create the BlogController by following the below command.

php artisan make:controller BlogController

The BlogController generate by Laravel into the “app/Http/Controllers” folder. Now, let’s open the BlogController and write the below code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Blog;

class BlogController extends Controller
{
    
	public function index(){
		$blogs = Blog::all();
		return view('blog.blogs',compact(['blogs']));
	}

	public function blogForm(){
		return view('blog.uploadfile');
	}

	public function uploadFile(Request $request){
		$request->validate([
            'title' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);
        
        $imageName = time().'.'.request()->image->getClientOriginalExtension();
        $request->image->move(public_path('images'), $imageName);

        Blog::insert([
        	'title' => $request->input('title'),
        	'image' => $imageName
        ]);

        return redirect()->route('blogs')
            ->with('success','Image uploaded successfully.')
            ->with('image',$imageName);
	}

}

Finally, We are ready with the Laravel BlogController. Now, We are going for creating the view file for the File Upload tutorial.

Laravel View

First of all, We need to create the blog directory inside the “resources/views” Folder. Then create the two views file like.

resources/views/blogs.blade.php
resources/views/uploadfile.blade.php

Now, let’s open the blogs.blade.php file and write the code like.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Blogs - File Lists</div>

                <div class="card-body">
                    @if (session('success'))
                        <div class="alert alert-success">
                            {{ session('success') }}
                        </div>
                    @endif

                    <a href="{{ route('uploadfile') }}" class="btn btn-success pull-right">Add Blog</a>
                    <div class="clearfix"></div>
                    <br>
                    <table class="table table-bordered">
                    	<tr>
                    		<th>Title</th>
                    		<th>Image</th>
                    	</tr>
                    	@foreach( $blogs as $key => $blog )
                		<tr>
                			<td>{{ $blog->title }}</td>
                			<td>
                				<img src="{{ asset('images/'.$blog->image) }}" style="width:50px; height:50px;">
                			</td>
                		</tr>
                    	@endforeach
                    </table>

                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, let’s open the uploadfile.blade.php File and write the code like.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">File Upload</div>

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

                    <form action="{{ route('uploadfile.post') }}" method="POST" enctype="multipart/form-data">
					    @csrf

					    <div class="form-group">
						    <label for="exampleInputEmail1">Blog Title</label>
						    <input type="text" name="title" class="form-control" id="title" placeholder="Blog Title" value="{{ old('title') }}">
						    <small id="emailHelp" class="form-text text-muted">Enter Blog Title</small>
						</div>
						<div class="form-group">
						    <label for="exampleInputEmail1">Image</label>
						    <input type="file" name="image" class="form-control-file">
						    <small id="emailHelp" class="form-text text-muted">Select Image file Jpeg, jpg, Png</small>
						</div>

						<button type="submit" class="btn btn-primary">Submit</button>

					</form>

                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Finally, We are ready with the Laravle File upload tutorial step by step. This tutorial is created only for Laravel beginners.

If you face any issue on Laravel File Upload writes the comment below.