Files Uploaded in Different Tabel Than Form

laravel file upload

File upload is an essential aspect of whatsoever project. Given this importance, information technology is surprising that many developers confront challenges of calculation file upload feature to their projects. In particular, developers are unsure most how to upload and validate files.

In this tutorial, I will discuss how to implement Laravel file upload functionality with multiple file and image uploading option. I volition use the Laravel storage folder and then create database record for uploading files. I will use Laravel v.five and Bootstrap to power the lawmaking of this tutorial.

  1. Prerequisites
  2. Create Model with Migration
  3. Item Model
  4. Create the Migration
  5. Model Of ItemDetails
  6. Migration of ItemDetails Table
  7. Database Configuration
  8. Prepare the Route
  9. Create the Controller
  10. View File (Upload_form.blade.php)
  11. Controller with Validation
  12. Storing Data and Files in Laravel
  13. With Validation
  14. Difference Between Local and Public Disks
  15. Manipulating files
  16. Sending Files as E-mail Attachments
  17. Create email sender course
  18. Create the email template

Yous might also similar: PHP File Upload with jQuery AJAX

Prerequisites

For the purpose of this tutorial, I presume that yous have a Laravel awarding installed on a web server. My setup is:

  • Linux/Unix or WAMP/XAMPP environment
  • Laravel 5.v
  • PHP vii.ane
  • MySQL
  • Web server (Apache, NGINX or integrated PHP web server for testing)

I take installed a Laravel app on a Cloudways managed Laravel server considering information technology has everything I'll need for this tutorial. If you exercise not take an account on Cloudways, sign up for free, and check out the following GIF to setup the server and application in just a few clicks.

DO installation

Create Model with Migration

I will first by creating the model and the tables in which I will save the files.

Launch the SSH terminal, go to the application's public root folder and blazon post-obit commands:

php artisan make:model Item -m php artisan brand:model ItemDetails -g

Particular Model

When the migration and the model accept been created successfully, become to app/Item.php and add together the following Model lawmaking to it:

<?php  namespace App;  use Illuminate\Database\Eloquent\Model;  class Item extends Model  {  protected $fillable = ['name'];  }

Create the Migration

Become to the database/migration folder and open the migration file for particular. You will see the default structure that include (in my instance) id , name, timestamps.

<?php  use Illuminate\Support\Facades\Schema;  apply Illuminate\Database\Schema\Blueprint;  use Illuminate\Database\Migrations\Migration;  form CreateItemsTable extends Migration  {  public function up()  {  Schema::create('items', part (Design $table) {  $table->increments('id');  $tabular array->cord('name');  $table->timestamps();  });  }  public function down()  {  Schema::drop('items');  }  }?>

Model Of ItemDetails

The model comprises of the post-obit code:

<?php  namespace App;  use Illuminate\Database\Eloquent\Model;  class ItemDetail extends Model  {  protected $fillable = ['item_id', 'filename'];  public role item()  {  return $this->belongsTo('App\Item');  }  }  ?>

In the above code, I used belongTO because itemDetails belongs to Item table and item_id is the foreign fundamental. This is known every bit inverse relation in Laravel.

Migration of ItemDetails Tabular array

Go to the database/migration folder and open the migration file for itemdetails. You will see the default structure that include id , name . timestamps.

<?php  use Illuminate\Support\Facades\Schema;  employ Illuminate\Database\Schema\Design;  use Illuminate\Database\Migrations\Migration;  form CreateItemDetailsTable extends Migration  {  /**  * Run the migrations.  *  * @return void  */  public function upwards()  {  Schema::create('item_details', function (Blueprint $table) {  $table->increments('id');  $table->integer('item_id')->unsigned();  $table->foreign('item_id')->references('id')->on('items');  $tabular array->string('filename');  $table->timestamps();  });  }  public function downwardly()  {  Schema::drib('item_details');  }  }  ?>

Next , In the app/Providers/AppServiceProvider.php file, the boot method set a default string length:

use Illuminate\Support\Facades\Schema;  public function boot()  {  Schema::defaultStringLength(191);  }

Database Configuration

In a Laravel powered app, database configuration is handled by two files: env and config/database.php. In my case, I created a database with the proper noun uploading. The Cloudways Database Managing director makes the entire process very easy.

Next, run the following command in the terminal to create tables in the database:

php artisan migrate

Now, when you bank check the database, you will run across that the tables take been created  successfully.

Yous might as well like: Connect Laravel with Firebase Existent Time Database

Fix the Route

Road sets the application URL and the controller method for this URL. Routes are located in route/web.php and contains the following code:

Route::get('/multiuploads', '[e-mail protected]');  Route::post('/multiuploads', '[e-mail protected]');

End Wasting Fourth dimension on Servers

Cloudways handle server management for you then you can focus on creating great apps and keeping your clients happy.

Create the Controller

Next, create the Controller by using the following command:

php artisan brand:controller UploadController

Side by side, go to app/Http/Controller/UploadController and open up the Controller file. Add the following code to it:

namespace App\Http\Controllers;  use Illuminate\Http\Request;  course UploadController extends Controller  {  public role uploadForm()  {  return view('upload_form');  }  public function uploadSubmit(Asking $request)  {  // coding ….  }  }

View File (Upload_form.bract.php)

In the view file, I take used Bootstrap for styling the lawmaking, link stylesheet , jQuery, JavaScript files.

<!doctype html>  <html lang="{{ app()->getLocale() }}">  <head>  <meta charset="utf-eight">  <meta http-equiv="X-UA-Uniform" content="IE=edge">  <meta proper noun="viewport" content="width=device-width, initial-scale=1">  <title>Laravel Uploading</championship>  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">  <!-- Optional theme -->  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.iii.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">  <!-- Fonts -->  <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">  <!-- Styles -->  <style>  .container {  margin-acme:2%;  }  </style>  </head>  <body>  @if (count($errors) > 0)  <div class="alert alert-danger">  <ul>  @foreach ($errors->all() as $error)  <li>{{ $error }}</li>  @endforeach  </ul>  </div>  @endif  <div class="container">  <div class="row">  <div class="col-md-2"> <img src="/32114.svg" width="80" /></div>  <div grade="col-md-viii"><h2>Laravel Multiple File Uploading With Bootstrap Form</h2>  </div>  </div>  <br>  <div form="row">  <div class="col-dr.-iii"></div>  <div form="col-md-half-dozen">  <course action="/multiuploads" method="postal service" enctype="multipart/grade-data">  {{ csrf_field() }}  <div class="form-group">  <label for="Production Proper noun">Product Proper name</label>  <input type="text" name="name" class="form-control"  placeholder="Production Name" >  </div>  <label for="Product Name">Product photos (can adhere more than one):</characterization>  <br />  <input type="file" class="form-control" proper name="photos[]" multiple />  <br /><br />  <input blazon="submit" class="btn btn-primary" value="Upload" />  </class>  </div>  </div>  </div>  </trunk>  </html>

Controller with Validation

I accept use Bootstrap classes for showing the warning for validation and employ Laravel Validation methods to validate the type of file. Use the following code for the controller:

<?php  namespace App\Http\Controllers;  apply App\Item;  use App\ItemDetail;  employ Illuminate\Http\Request;  form UploadController extends Controller  {  public function uploadForm()  {  return view('upload_form');  }  public office uploadSubmit(Request $request)  {  $this->validate($asking, [  'proper noun' => 'required',  'photos'=>'required',  ]);  if($request->hasFile('photos'))  {  $allowedfileExtension=['pdf','jpg','png','docx'];  $files = $request->file('photos');  foreach($files every bit $file){  $filename = $file->getClientOriginalName();  $extension = $file->getClientOriginalExtension();  $cheque=in_array($extension,$allowedfileExtension);  //dd($check);  if($bank check)  {  $items= Item::create($request->all());  foreach ($request->photos as $photograph) {  $filename = $photograph->store('photos');  ItemDetail::create([  'item_id' => $items->id,  'filename' => $filename  ]);  }  echo "Upload Successfully";  }  else  {  echo '<div class="alert alert-warning"><strong>Warning!</strong> Lamentable Only Upload png , jpg , medico</div>';  }  }  }  }  }?>        

Storing Information and Files in Laravel

Laravel provides a storage filesystem that stores all the information including files and images.

For this, Laravel provides config/filesystems.php, located in the config folder. In this file, you can specify the locations for your file storage.

render [  'default' => 'local',  'disks' => [  'local' => [  'driver' => 'local',  'root' => storage_path('app'),  ],  // ...

Using the above code snippet, yous could save the files in app/storage folder instead of the public folder. This is a good coding practice for storing information because this location is inaccessible from the browser. For the purpose of this tutorial, I have created a folder with the proper name photos in storage/app/.

When the run the app in the browser, you lot volition see the post-obit screens:

Multiple laravel image file upload

With Validation

laravel file upload validation

laravel multiple file upload form

laravel file upload error

To see the image and file upload in Laravel in action, check out the demo.

Divergence Between Local and Public Disks

Y'all can see the disks local and public defined in config/filesystems.php. Laravel uses the local disk configuration by default. The underlying difference between local and public disk is that local disk is individual and tin't be accessed from the browser, whereas the public disk can exist hands accessed from the browser.

Since the public deejay is in storage/app/public and Laravel's server root is in public, y'all demand to link storage/app/public to Laravel's public folder. We tin can do by running php artisan storage:link.

Manipulating files

Laravel largely needs external help in resizing images, adding filters and other related operations. Calculation these feature to the native environment of Laravel will only bloat the application since there isn't any installs needed. For that, we need a package chosen intervention/prototype. Before higher up, we accept already installed this package, merely notwithstanding composer requires it for reference.

Nosotros don't need to register annihilation since Laravel can automatically observe packages. Read the post-obit if y'all are using lesser version than Laravel five.5.

To resize an image

$prototype = Image::make(storage_path('app/public/contour.jpg'))->resize(300, 200);

Fifty-fifty Laravel's packages are fluent.

Sending Files as Email Attachments

For transport files with attachments you just paste the following lawmaking in your controller co-ordinate to input fields.

<?php  ...  ...  public function uploadDocument(Request $request) {     $title = $request->file('name');          // Get the uploades file with proper name document     $certificate = $request->file('document');       // Required validation     $request->validate([         'name' => 'required|max:255',         'document' => 'required'     ]);       // Check if uploaded file size was greater than     // maximum immune file size     if ($document->getError() == i) {         $max_size = $certificate->getMaxFileSize() / 1024 / 1024;  // Become size in Mb         $error = 'The document size must be less than ' . $max_size . 'Mb.';         return redirect()->back()->with('flash_danger', $error);     }          $information = [         'document' => $document     ];          // If upload was successful     // ship the e-mail     $to_email = [email protected];     \Mail::to($to_email)->send(new \App\Postal service\Upload($data));     return redirect()->back()->with('flash_success', 'Your certificate has been uploaded.');  }

Create email sender class

To transport the electronic mail in Laravel, you need to create a separate form file. This class volition have the functionality to prepare email and its body. Likewise we will attach the uploaded file as inline attachment.

Here is my email class:

<?php  #App\Post\Upload.php  namespace App\Mail;  utilize Illuminate\Bus\Queueable;  utilise Illuminate\Postal service\Mailable;  use Illuminate\Queue\SerializesModels;  class Upload extends Mailable  {     utilize Queueable, SerializesModels;     protected $data;     /**      * Create a new message example.      *      * @return void      */     public part __construct($data=[])     {         $this->information = $data;     }       /**      * Build the message.      *      * @return $this      */     public function build()     {         return $this->view('emails/upload')                 ->subject('Document Upload')                 ->attach($this->information['document']->getRealPath(),                 [                     'every bit' => $this->data['certificate']->getClientOriginalName(),                     'mime' => $this->data['document']->getClientMimeType(),                 ]);     }  }

The of import functions used here are:

– getRealPath(): Become the temporary upload path  – getClientOriginalName(): Become the name of uploaded file  – getClientMimeType(): Go the mime type of uploaded file

Create the e-mail template

In the higher up step, our electronic mail class refers to the e-mail template as render $this->view('emails/upload'). So we volition create the email template at resource/views/emails/upload.blade.php

#resource/views/emails/upload.bract.php  <p>Hi,</p>  <p>Please download the attached file.</p>  <p>Thanks</p>

At present when y'all submit the form, your uploaded file will be sent an email attachment.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

"Cloudways hosting has one of the best customer service and hosting speed"

Sanjit C [Website Developer]

Pardeep Kumar

Pardeep is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He honey to work on Open up source platform , Frameworks and working on new ideas. You can e-mail him at [email protected]

kinneygack1968.blogspot.com

Source: https://www.cloudways.com/blog/laravel-multiple-files-images-upload/

0 Response to "Files Uploaded in Different Tabel Than Form"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel