Php

How To Upload File in Laravel 9 Using MySQL

This tutorial help to upload files using Laravel 9. We will create an HTML form view that upload file into the server and save path information into a MySQL table.

We will use MySQL and PHP 7 to create file upload functionality.

File Upload Using Laravel 9 and Mysql

Let’s create a new laravel application using laravel CLI. The Artisan is the command-line interface included with Laravel, If you have not yet created a Laravel application. Please create using the command below –

laravel new laravel_file_upload

Create Migration Table

These two options to create a MySQL table for laravel application, Either You will create a table into MySQL using SQL script or using migration, I prefer the migration option –

The uploads table SQL script:

CREATE TABLE `uploads` (
  `id` int(10) UNSIGNED NOT NULL,
  `user_id` int(10) UNSIGNED NOT NULL,
  `group_id` int(10) UNSIGNED NOT NULL,
  `filename` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `extension` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `filesize` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `location` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Using Migration File in Laravel

We will create a migration file using the below command –

php artisan make:migration create_uploads_table --create=uploads

Now, open the file database/migrations/{{datetime}}_create_uploads_table.php. We will add the below code inside the up() method.

Schema::create('uploads', function (Blueprint $table) {
      $table->increments('id');
   $table->integer('user_id');
   $table->integer('group_id');
      $table->string('filename');
   $table->string('extension');
   $table->string('filesize');
   $table->string('location');
      $table->timestamps();
});

Open a command line and run the below command
php artisan migrate

Related Post

The above command will create a table in the MySQL database.

Model File into Laravel

We will create FileUpload.php into Models/ folder the file location would be app/Models/FileUpload.php. Open the file and add the below code into this file.

//Models/FileUpload.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class FileUpload extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */    protected $fillable = [
        'user_id', 'group_id', 'filename', 'extension', 'filesize', 'location'
    ];
}

Create Routes and View file into Laravel

We will create a view file to display the upload form into laravel. We will use the session to display upload success and error messages.

We will create a view file inside the resources/views folder. We will add below into uploads.blade.php file.

@extends('layouts.backend')

@section('title', 'Add Contacts')

@section('content')

<div>
    @include('flash::message')

    <!-- Start Page Content -->

<div class="sms_heading">

<h3><i class="fa fa-at"></i> Add Contacts</h3>

</div>

    @if ($message = Session::get('success'))


<div class="alert alert-success alert-block">

            <button type="button" class="close" data-dismiss="alert">×</button>

            <strong>{{ $message }}</strong>

</div>


    @endif

<div class="tab-content">


<div role="tabpanel" class="tab-pane active" id="upload-contacts">
            <form action="{{ route('upload-file', $group) }}" class="form-horizontal form-bordered" id="upload-contacts" method="post" enctype="multipart/form-data">
                <input name="_token" type="hidden" value="{{ csrf_token() }}">

<div class="form-group">

<div class="col-xs-12 col-sm-9 col-md-6">
                        <input type="file" class="filestyle" id="filename" name="filename" data-buttontext="Browse">
</div>

</div>


<div class="form-actions fluid">

<div class="row">

<div class="col-md-12">

<div class="col-sm-12 col-md-12">
                                <button class="btn btn-info" type="submit"><i class="fa fa-upload"></i> Upload Contacts File</button>
</div>

</div>

</div>

</div>

            </form>
</div>

        
        @if (count($errors) &gt; 0)

<div class="alert alert-danger">
                <strong>Whoops!</strong> There were some problems with your input.


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

  <li>{{ $error }}</li>

                    @endforeach
</ul>

</div>

        @endif
</div>

    <!-- End Page Content -->  
</div>

@stop

Routes in Laravel 9

We will define routes in routes/web.php file. This route path will use to upload files into the server.

Route::post('groups/{group}/contacts/upload', 'UploadContactsController')->name('upload-file');

Now, We will create UploadContactsController.php file and define upload-file method.

//App\Http\Controllers\Backend\UploadContactController.php
namespace App\Http\Controllers\Backend;

use App\Http\Requests\Backend\Contacts\UploadContactsRequest;
use App\Http\Controllers\Controller;
use App\Jobs\UploadContacts;
use App\Models\FileUpload;
use App\Models\Group;
use Session;
class UploadContactsController extends Controller
{
    /**
     * Upload the contacts file
     *
     * @param  App\Http\Requests\Backend\Contacts\UploadContactsRequest $request
     * @param  App\Models\Group $group
     * @return \Illuminate\Http\Response
     */    public function __invoke(UploadContactsRequest $request, Group $group)
    {
        if ($request--->file('filename')-&gt;isValid()) {

            $fileUpload = new FileUpload;
            $fileUpload->user_id = auth()->user()->id;
            $fileUpload->group_id = $group->id;
            $fileUpload->filename = $request->file('filename')->hashName();
            $fileUpload->extension = $request->file('filename')->extension();
            $fileUpload->filesize = $request->file('filename')->getClientSize();
            $fileUpload->location = $request->file('filename')->store('contact-files');
            $fileUpload->save();
            toastr()->success('Data has been saved successfully!');

            flash()->success('Your file is currently being processed. You will be notified when done.');

            //UploadContacts::dispatch($fileUpload, $group)->onQueue('file-uploads');
            dispatch(new UploadContacts($fileUpload, $group))->onQueue('file-uploads');
        } else {
            flash()->error('There was a problem uploading your file. Please try again.');
        }

        return back();
    }
}

Now we will define the request class into Http\Request\Backend\Contact. We will create UploadContactsRequest.php file into this folder.

//App\Http\Requests\Backend\Contacts\UploadContactRequest.php
 <?php

namespace App\Http\Requests\Backend\Contacts;

use Illuminate\Foundation\Http\FormRequest;

class UploadContactsRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */    public function rules()
    {
        $mime_types = [
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/vnd.ms-excel.addin.macroenabled.12',
            'application/vnd.ms-excel.sheet.binary.macroenabled.12',
            'application/vnd.ms-excel.sheet.macroenabled.12',
            'application/vnd.oasis.opendocument.spreadsheet',
            'text/csv',
            'text/plain'
        ];

        return [
            'filename' =--> 'required|file|mimetypes:'.implode($mime_types,',').'|max:51200'
        ];
    }
}
Tags: laravel 5

Recent Posts

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

2 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

2 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

2 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

3 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

3 months ago

Common Practices for Laravel Blade Template

in this Laravel tutorial, I will explore common practices for using the Laravel Blade template with examples. Blade is a… Read More

3 months ago

Categories