Why Not to Use Tables to Upload Image
Hi everybody! Today we are going to build a file upload application in Laravel 7 with the use of Laravel Livewire.
I ever found it hard to build file upload systems with JavaScript frontend frameworks like Vuejs. Luckily is it super easy to implement with Laravel Livewire.
Since final week Laravel Livewire added support for file uploads out of the box. Today nosotros are going to build a file upload system with Laravel Livewire. We are uploading images to the server and saving the path of the images to the database. In this style nosotros get a list of uploaded images. The consequence should wait something like this:
Let's create a project
Nosotros are going to code a real application to test Laravel Livewire's file upload possibilities. We beginning by creating a new Laravel projection laravel new <project proper name>
.
Then we add together the database credentials in the .env
file. My .env
file looks like this:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel7-livewire-file-upload DB_USERNAME=root DB_PASSWORD=*******
For the styling we are going to use Tailwindcss. I don't going to cover how to install Tailwindcss. If you desire a guide on installing Tailwindcss follow this tutorial.
Create model and migrations
We are going to create a photo model with an database migration php artisan brand:model Photo -m
.
In the freshly created model we are calculation the post-obit lawmaking to the file.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Photo extends Model { protected $fillable = [ 'file_name' ]; }
And then nosotros open up the database migration file and add the post-obit database fields.
Schema::create('photos', function (Blueprint $table) { $table->id(); $table->string('file_name'); $table->timestamps(); });
Now we need to run php artisan migrate
to create the database tables.
With this out of the way we can install Laravel Livewire and start edifice the file upload mechanism.
Install Livewire
The installation of Laravel Livewire is super easy.
Add together the package by running composer crave livewire/livewire
.
We need to include the JavaScript on every page we are going to use Livewire. Create a new layouts
binder inside the resource/views
directory.
In the resources/views/layouts
binder we are going to create a new file called app.blade.php
With the post-obit lawmaking:
<!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta proper name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</championship> <!-- Scripts --> <script src="{{ asset('js/app.js') }}" defer> </script> <!-- Fonts --> <link rel="dns-prefetch" href="//fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet"> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> @livewireStyles </head> <body> <div id="app" grade="flex min-h-screen bg-gray-200"> @yield('content') </div> @livewireScripts </body> </html>
Make the components
Now nosotros need to brand a livewire component. Run php artisan make:livewire image-upload
. This command volition create the following files in our projection:
app/http/Livewire/ImageUpload.php
resources/views/livewire/image-upload.bract.php
Nosotros can render a Livewire component as a component on a page. But since we only have the search component on the page, we are going to use Livewire routing.
Replace the code in the routes/web.php
file with the following code:
<?php use Illuminate\Back up\Facades\Road; Route::livewire('/', 'image-upload');
Livewire component design
Now it is time to add this code to the epitome-upload.bract.php
file.
<div class="due west-full mt-12"> <div class="container max-west-2xl mx-auto"> @if (session()->has('message')) <div course="flex items-centre px-four py-3 mb-vi text-sm font-bold text-white bg-dark-green-500 rounded" role="alert"> <svg class="w-four h-4 mr-two fill-electric current" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20 "><path d=" M12.432 0c1.34 0 ii.01 .912 2.01 one.957 0 1.305 -i.164 two.512 -2.679 2.512 -i.269 0 -two.009 -.75 -1.974 -ane. 99C9.789 1.436 10.67 0 12.432 0zM8.309 20c-one.058 0 -i.833 -.652 -1.093 -iii. 524l1.214-5.092c.211-.814.246-1.141 0 -ane.141 -.317 0 -1.689 .562 -2.502 1. 117l-.528-.88c2.572-2.186 v.531 -three.467 6.801 -3.467 ane.057 0 1.233 1.273 .705 3. 23l-1.391 v. 352c-.246.945-.141 i.271 .106 one.271 .317 0 ane.357 -.392 two.379 -ane. 207l.6.814C12.098 nineteen.02 nine.365 20 viii.309 20z"/></svg> <p>{{ session('message') }}</p> </div> @endif <div class="p-6 mb-12 bg-white border rounded-md shadow-twoscore"> <form wire:submit.forestall="save"> <div course="mb-3"> <input type="file" wire:model="photo" form=""> <div> @fault('photo') <bridge course="text-sm italic text-red-500">{{ $message }}</bridge>@enderror </div> <div wire:loading wire:target="photo" form="text-sm italic text-greyness-500">Uploading...</div> </div> <button type="submit" class="px-four py-2 font-bold text-white bg-blueish-500 rounded hover:bg-bluish-700">Save Photo</button> </grade> </div> <div class="flex flex-wrap -mx-2"> @foreach($photos as $photo) <div grade="w-1/2 p-2"> <div grade="w-total h-full border"> <img src="{{ nugget('storage/photos/' . $photograph->file_name) }}"> </div> </div> @endforeach </div> </div> </div>
Nosotros create a elementary file upload form. We use wire:submit.prevent
to handle the form submit with Laravel Livewire. Nosotros bind Livewire to the file input with wire:model="photo"
.
Beneath the file upload form we generate a listing of stored photos. We do this by looping trough the $photos
assortment.
As well, annotation that we have a little alarm at the top. We will show a message when the image is successfully uploaded.
Livewire component logic
Next, nosotros volition add the logic in the ImageUpload.php
file.
<?php namespace App\Http\Livewire; use Livewire\Component; use Livewire\WithFileUploads; use App\Photo; course ImageUpload extends Component { use WithFileUploads; public $photo; public part save () { $this->validate([ 'photograph' => 'image|max:1024', ]); $proper noun = md5($this->photograph . microtime()).'.'.$this->photo->extension(); $this->photo->storeAs('photos', $name); Photo::create(['file_name' => $proper noun]); session()->flash('message', 'The photograph is successfully uploaded!'); } public function render () { render view('livewire.epitome-upload', [ 'photos' => Photograph::all(), ]); } }
Showtime, nosotros validate the submitted file. We check if information technology is an image and that the image is non too big.
And so we create a unique name for the epitome. We do this by hashing the current micro time and adding the file extension.
Then we upload the file to the server and place the name of the photo in the database.
Then we flash a bulletin that the photograph is successfully uploaded to the server.
Linking the storage
If you try to upload a file y'all will see that it is non working yet. To make this all working we must add together a symbolic link to the path where we store the photos.
Open config/filesystems.php
and add the post-obit lawmaking in the links assortment.
'links' => [ public_path('storage') => storage_path('app/public'), public_path('storage/photos') => storage_path('app/photos'), ],
So we run the php artisan storage:link
command. This will create the symbolic link.
Now the file uploading system should work. Yous can upload photos and the photos will brandish in the listing beneath the file upload form.
Wrapping it upwardly
Today nosotros accept learned how to use Livewire file uploads. You can find the source code on GitHub. If you want to acquire more than nearly Livewire, checkout this tutorial well-nigh searching in Livewire.
If you have any questions, delight let me know in the comments. You can also achieve out to me on twitter.
Source: https://www.larapeak.com/blog/upload-files-and-photos-with-laravel-livewire
0 Response to "Why Not to Use Tables to Upload Image"
Post a Comment