Laravel Upload Files if No Folder Make Folder
Hello everybody! Today nosotros are going to build a file upload application in Laravel 7 with the utilise of Laravel Livewire.
I ever found it difficult to build file upload systems with JavaScript frontend frameworks similar Vuejs. Luckily is it super easy to implement with Laravel Livewire.
Since terminal 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 way we go a list of uploaded images. The result should look something like this:
Let's create a projection
We are going to code a real awarding to test Laravel Livewire'south file upload possibilities. We start by creating a new Laravel project laravel new <projection proper name>.
And so nosotros add the database credentials in the .env file. My .env file looks similar 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 nosotros are going to use Tailwindcss. I don't going to cover how to install Tailwindcss. If you want 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 make:model Photograph -m.
In the freshly created model nosotros are adding the following code to the file.
<?php namespace App; employ Illuminate\Database\Eloquent\Model; class Photo extends Model { protected $fillable = [ 'file_name' ]; } Then nosotros open the database migration file and add together the post-obit database fields.
Schema::create('photos', function (Blueprint $tabular array) { $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 style nosotros can install Laravel Livewire and start building the file upload mechanism.
Install Livewire
The installation of Laravel Livewire is super piece of cake.
Add the package by running composer require livewire/livewire.
We need to include the JavaScript on every folio nosotros are going to use Livewire. Create a new layouts folder inside the resources/views directory.
In the resource/views/layouts folder we are going to create a new file chosen app.blade.php With the post-obit code:
<!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <caput> <meta charset="utf-viii"> <meta proper name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta proper noun="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Scripts --> <script src="{{ nugget('js/app.js') }}" defer> </script> <!-- Fonts --> <link rel="dns-prefetch" href="//fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css?family unit=Nunito" rel="stylesheet"> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> @livewireStyles </head> <body> <div id="app" class="flex min-h-screen bg-gray-200"> @yield('content') </div> @livewireScripts </body> </html> Make the components
Now we need to make a livewire component. Run php artisan make:livewire image-upload. This command volition create the post-obit files in our project:
app/http/Livewire/ImageUpload.php
resources/views/livewire/image-upload.blade.php
Nosotros tin can render a Livewire component as a component on a folio. Just since we but have the search component on the page, we are going to utilise Livewire routing.
Replace the code in the routes/web.php file with the following code:
<?php use Illuminate\Support\Facades\Road; Route::livewire('/', 'image-upload'); Livewire component design
At present it is time to add together this code to the paradigm-upload.blade.php file.
<div class="w-full mt-12"> <div class="container max-westward-2xl mx-auto"> @if (session()->has('message')) <div class="flex items-center px-iv py-3 mb-6 text-sm font-assuming text-white bg-green-500 rounded" role="alert"> <svg grade="west-4 h-4 mr-two make full-current" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20 "><path d=" M12.432 0c1.34 0 2.01 .912 2.01 one.957 0 1.305 -1.164 two.512 -ii.679 ii.512 -ane.269 0 -ii.009 -.75 -ane.974 -one. 99C9.789 1.436 10.67 0 12.432 0zM8.309 20c-1.058 0 -ane.833 -.652 -1.093 -3. 524l1.214-v.092c.211-.814.246-1.141 0 -ane.141 -.317 0 -1.689 .562 -two.502 one. 117l-.528-.88c2.572-two.186 5.531 -iii.467 6.801 -iii.467 1.057 0 ane.233 i.273 .705 3. 23l-1.391 5. 352c-.246.945-.141 1.271 .106 1.271 .317 0 1.357 -.392 two.379 -1. 207l.6.814C12.098 nineteen.02 ix.365 xx 8.309 20z"/></svg> <p>{{ session('bulletin') }}</p> </div> @endif <div class="p-6 mb-12 bg-white border rounded-md shadow-xl"> <form wire:submit.prevent="save"> <div form="mb-3"> <input blazon="file" wire:model="photograph" class=""> <div> @error('photo') <span class="text-sm italic text-crimson-500">{{ $message }}</bridge>@enderror </div> <div wire:loading wire:target="photo" grade="text-sm italic text-gray-500">Uploading...</div> </div> <button blazon="submit" class="px-iv py-2 font-bold text-white bg-blue-500 rounded hover:bg-blue-700">Save Photo</button> </form> </div> <div class="flex flex-wrap -mx-2"> @foreach($photos as $photo) <div form="w-1/2 p-2"> <div class="w-total h-full border"> <img src="{{ asset('storage/photos/' . $photograph->file_name) }}"> </div> </div> @endforeach </div> </div> </div> We create a simple file upload grade. We use wire:submit.foreclose to handle the form submit with Laravel Livewire. We bind Livewire to the file input with wire:model="photo".
Below the file upload form nosotros generate a list of stored photos. We do this past looping trough the $photos assortment.
Also, annotation that nosotros have a little alarm at the top. We will prove a message when the image is successfully uploaded.
Livewire component logic
Next, we will add the logic in the ImageUpload.php file.
<?php namespace App\Http\Livewire; use Livewire\Component; use Livewire\WithFileUploads; use App\Photo; form ImageUpload extends Component { use WithFileUploads; public $photo; public function relieve () { $this->validate([ 'photo' => 'paradigm|max:1024', ]); $name = md5($this->photo . microtime()).'.'.$this->photo->extension(); $this->photo->storeAs('photos', $name); Photograph::create(['file_name' => $proper noun]); session()->flash('message', 'The photo is successfully uploaded!'); } public function return () { return view('livewire.image-upload', [ 'photos' => Photo::all(), ]); } } First, nosotros validate the submitted file. We check if it is an epitome and that the image is not too big.
Then we create a unique name for the image. We do this past hashing the current micro fourth dimension and adding the file extension.
Then we upload the file to the server and identify the name of the photo in the database.
And then we wink a message that the photo is successfully uploaded to the server.
Linking the storage
If you effort 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 up config/filesystems.php and add together the following code in the links array.
'links' => [ public_path('storage') => storage_path('app/public'), public_path('storage/photos') => storage_path('app/photos'), ], Then nosotros run the php artisan storage:link command. This will create the symbolic link.
Now the file uploading arrangement should work. You tin can upload photos and the photos will display in the list beneath the file upload form.
Wrapping information technology up
Today we have learned how to use Livewire file uploads. You can find the source code on GitHub. If you want to learn more about Livewire, checkout this tutorial nigh searching in Livewire.
If you have whatever questions, please permit me know in the comments. You can also reach out to me on twitter.
Source: https://www.larapeak.com/blog/upload-files-and-photos-with-laravel-livewire
0 Response to "Laravel Upload Files if No Folder Make Folder"
Postar um comentário