Upload Multiple Photos One at a Time Php
File upload is an essential aspect of any project. Given this importance, it is surprising that many developers face challenges of adding file upload feature to their projects. In detail, developers are unsure near how to upload and validate files.
In this tutorial, I volition discuss how to implement Laravel file upload functionality with multiple file and paradigm uploading option. I will use the Laravel storage folder and and so create database record for uploading files. I will use Laravel 5.five and Bootstrap to power the lawmaking of this tutorial.
- Prerequisites
- Create Model with Migration
- Particular Model
- Create the Migration
- Model Of ItemDetails
- Migration of ItemDetails Table
- Database Configuration
- Set up the Route
- Create the Controller
- View File (Upload_form.blade.php)
- Controller with Validation
- Storing Information and Files in Laravel
- With Validation
- Difference Betwixt Local and Public Disks
- Manipulating files
- Sending Files as Email Attachments
- Create email sender grade
- Create the email template
You might also like: PHP File Upload with jQuery AJAX
Prerequisites
For the purpose of this tutorial, I assume that you take a Laravel application installed on a web server. My setup is:
- Linux/Unix or WAMP/XAMPP surroundings
- Laravel five.five
- PHP 7.1
- MySQL
- Web server (Apache, NGINX or integrated PHP web server for testing)
I have installed a Laravel app on a Cloudways managed Laravel server because it has everything I'll demand for this tutorial. If y'all exercise not have an account on Cloudways, sign upward for gratis, and check out the post-obit GIF to setup the server and application in just a few clicks.
Create Model with Migration
I volition start past creating the model and the tables in which I will save the files.
Launch the SSH last, get to the application'due south public root binder and type post-obit commands:
php artisan make:model Item -k php artisan make:model ItemDetails -thousand
Detail Model
When the migration and the model have been created successfully, go to app/Item.php and add the following Model lawmaking to it:
<?php namespace App; utilize Illuminate\Database\Eloquent\Model; course Item extends Model { protected $fillable = ['name']; } Create the Migration
Go to the database/migration folder and open the migration file for detail. You will see the default structure that include (in my case) id , proper noun, timestamps.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateItemsTable extends Migration { public function upwards() { Schema::create('items', office (Blueprint $table) { $table->increments('id'); $table->cord('name'); $table->timestamps(); }); } public function down() { Schema::drop('items'); } }?> Model Of ItemDetails
The model comprises of the following code:
<?php namespace App; use Illuminate\Database\Eloquent\Model; course ItemDetail extends Model { protected $fillable = ['item_id', 'filename']; public function item() { return $this->belongsTo('App\Item'); } } ?> In the above code, I used belongTO because itemDetails belongs to Item table and item_id is the strange key. This is known as inverse relation in Laravel.
Migration of ItemDetails Table
Go to the database/migration folder and open up the migration file for itemdetails. You lot will see the default structure that include id , name . timestamps.
<?php utilize Illuminate\Back up\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateItemDetailsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { 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'); $tabular array->timestamps(); }); } public function down() { Schema::driblet('item_details'); } } ?> Next , In the app/Providers/AppServiceProvider.php file, the kicking method set a default string length:
apply Illuminate\Support\Facades\Schema; public function kicking() { 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 name uploading. The Cloudways Database 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 lot check the database, you lot will come across that the tables have been created successfully.
Y'all might also like: Connect Laravel with Firebase Real Time Database
Set up the Road
Route sets the application URL and the controller method for this URL. Routes are located in route/web.php and contains the following code:
Route::become('/multiuploads', '[e-mail protected]'); Route::mail service('/multiuploads', '[email protected]'); Stop Wasting Time on Servers
Cloudways handle server management for you then you can focus on creating corking apps and keeping your clients happy.
Create the Controller
Next, create the Controller by using the following command:
php artisan brand:controller UploadController
Next, go to app/Http/Controller/UploadController and open the Controller file. Add the following code to it:
namespace App\Http\Controllers; use Illuminate\Http\Request; form UploadController extends Controller { public office uploadForm() { return view('upload_form'); } public function uploadSubmit(Request $asking) { // coding …. } } View File (Upload_form.blade.php)
In the view file, I have used Bootstrap for styling the code, link stylesheet , jQuery, JavaScript files.
<!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="Ten-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel Uploading</title> <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.seven/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="bearding"> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> <!-- Styles --> <way> .container { margin-top:ii%; } </style> </head> <torso> @if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $mistake }}</li> @endforeach </ul> </div> @endif <div class="container"> <div class="row"> <div grade="col-md-2"> <img src="/32114.svg" width="80" /></div> <div form="col-medico-8"><h2>Laravel Multiple File Uploading With Bootstrap Form</h2> </div> </div> <br> <div class="row"> <div class="col-dr.-iii"></div> <div grade="col-md-half-dozen"> <form action="/multiuploads" method="post" enctype="multipart/class-data"> {{ csrf_field() }} <div class="form-group"> <label for="Product Name">Product Name</label> <input type="text" proper noun="name" class="form-control" placeholder="Product Proper name" > </div> <characterization for="Product Proper name">Product photos (tin can attach more than 1):</label> <br /> <input type="file" class="form-control" name="photos[]" multiple /> <br /><br /> <input type="submit" form="btn btn-primary" value="Upload" /> </class> </div> </div> </div> </trunk> </html> Controller with Validation
I have apply Bootstrap classes for showing the alert for validation and utilise Laravel Validation methods to validate the type of file. Use the following code for the controller:
<?php namespace App\Http\Controllers; employ App\Item; use App\ItemDetail; use Illuminate\Http\Request; class UploadController extends Controller { public role uploadForm() { return view('upload_form'); } public office uploadSubmit(Asking $asking) { $this->validate($request, [ 'name' => 'required', 'photos'=>'required', ]); if($request->hasFile('photos')) { $allowedfileExtension=['pdf','jpg','png','docx']; $files = $request->file('photos'); foreach($files as $file){ $filename = $file->getClientOriginalName(); $extension = $file->getClientOriginalExtension(); $bank check=in_array($extension,$allowedfileExtension); //dd($check); if($check) { $items= Detail::create($asking->all()); foreach ($request->photos as $photo) { $filename = $photo->store('photos'); ItemDetail::create([ 'item_id' => $items->id, 'filename' => $filename ]); } echo "Upload Successfully"; } else { echo '<div grade="warning alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , physician</div>'; } } } } }?> Storing Data and Files in Laravel
Laravel provides a storage filesystem that stores all the data 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.
return [ 'default' => 'local', 'disks' => [ 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), ], // ... Using the above code snippet, y'all could save the files in app/storage folder instead of the public binder. This is a practiced coding do for storing data because this location is inaccessible from the browser. For the purpose of this tutorial, I have created a folder with the name photos in storage/app/.
When the run the app in the browser, y'all will encounter the following screens:
With Validation
To run into the epitome and file upload in Laravel in action, check out the demo.
Difference Between Local and Public Disks
Y'all can run into 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 be easily accessed from the browser.
Since the public disk is in storage/app/public and Laravel'southward server root is in public, yous demand to link storage/app/public to Laravel's public folder. Nosotros 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. Adding these feature to the native environment of Laravel volition only bloat the application since there isn't whatsoever installs needed. For that, we need a parcel called intervention/prototype. Earlier in a higher place, we have already installed this package, but still composer requires it for reference.
We don't demand to register anything since Laravel tin can automatically detect packages. Read the following if you are using bottom version than Laravel 5.v.
To resize an image
$image = Paradigm::make(storage_path('app/public/profile.jpg'))->resize(300, 200); Even Laravel's packages are fluent.
Sending Files as Email Attachments
For transport files with attachments you only paste the post-obit code in your controller co-ordinate to input fields.
<?php ... ... public office uploadDocument(Asking $request) { $championship = $request->file('name'); // Get the uploades file with proper name document $document = $request->file('document'); // Required validation $request->validate([ 'name' => 'required|max:255', 'document' => 'required' ]); // Check if uploaded file size was greater than // maximum allowed file size if ($document->getError() == one) { $max_size = $document->getMaxFileSize() / 1024 / 1024; // Go size in Mb $error = 'The document size must be less than ' . $max_size . 'Mb.'; return redirect()->dorsum()->with('flash_danger', $error); } $data = [ 'document' => $document ]; // If upload was successful // send the email $to_email = [electronic mail protected]; \Mail::to($to_email)->transport(new \App\Mail\Upload($information)); return redirect()->back()->with('flash_success', 'Your document has been uploaded.'); } Create electronic mail sender class
To send the e-mail in Laravel, you need to create a separate class file. This grade will take the functionality to ready e-mail and its body. Too we will adhere the uploaded file as inline attachment.
Here is my email class:
<?php #App\Mail service\Upload.php namespace App\Mail service; use Illuminate\Bus\Queueable; employ Illuminate\Mail service\Mailable; use Illuminate\Queue\SerializesModels; class Upload extends Mailable { use Queueable, SerializesModels; protected $information; /** * Create a new message instance. * * @return void */ public part __construct($data=[]) { $this->data = $data; } /** * Build the message. * * @return $this */ public role build() { return $this->view('emails/upload') ->subject('Document Upload') ->attach($this->data['certificate']->getRealPath(), [ 'every bit' => $this->data['document']->getClientOriginalName(), 'mime' => $this->information['document']->getClientMimeType(), ]); } } The of import functions used here are:
– getRealPath(): Go the temporary upload path – getClientOriginalName(): Get the proper noun of uploaded file – getClientMimeType(): Become the mime type of uploaded file
Create the email template
In the in a higher place step, our email class refers to the email template equally render $this->view('emails/upload'). And then we will create the email template at resources/views/emails/upload.blade.php
#resource/views/emails/upload.blade.php <p>Hi,</p> <p>Please download the attached file.</p> <p>Thanks</p>
At present when you submit the form, your uploaded file volition be sent an email attachment.
Share your stance in the comment department. COMMENT At present
Share This Article
Customer Review at
"Cloudways hosting has i of the best customer service and hosting speed"
Sanjit C [Website Developer]
Pardeep Kumar
Pardeep is a PHP Customs Manager at Cloudways - A Managed PHP Hosting Platform. He love to piece of work on Open source platform , Frameworks and working on new ideas. You can email him at [email protected]
courtneytheigiche42.blogspot.com
Source: https://www.cloudways.com/blog/laravel-multiple-files-images-upload/
0 Response to "Upload Multiple Photos One at a Time Php"
Post a Comment