Laravel Validation File Upload Doc File Cannot Be Uploaded Liver Server

Howdy everybody! Today we are going to build a file upload application in Laravel 7 with the use of Laravel Livewire.

I e'er found it difficult to build file upload systems with JavaScript frontend frameworks like 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 we 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 fashion we get a list of uploaded images. The result should look something like this:

The result

Permit'due south create a projection

We are going to code a real application to test Laravel Livewire'south file upload possibilities. We commencement by creating a new Laravel project laravel new <project name>.

And then nosotros add 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 apply Tailwindcss. I don't going to cover how to install Tailwindcss. If y'all 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 -yard.

In the freshly created model we are adding the following lawmaking to the file.

                                    <?php              namespace              App;              apply              Illuminate\Database\Eloquent\Model;                              class                Photo                extends                Model              {              protected              $fillable = [              'file_name'              ]; }                              

Then we open the database migration file and add the following database fields.

          Schema::create('photos',                          function              (Pattern $table)            {     $table->id();     $tabular array->string('file_name');     $tabular array->timestamps(); });                  

At present we need to run php artisan migrate to create the database tables.

With this out of the way nosotros tin install Laravel Livewire and start building the file upload machinery.

Install Livewire

The installation of Laravel Livewire is super easy.

Add the package by running composer require livewire/livewire.

We demand to include the JavaScript on every folio nosotros are going to use Livewire. Create a new layouts folder within the resources/views directory.

In the resources/views/layouts folder we are going to create a new file called app.blade.php With the following lawmaking:

                      <!doctype              html>            <html              lang="{{ str_replace('_', '-', app()->getLocale()) }}">            <head>            <meta              charset="utf-viii">            <meta              name="viewport"              content="width=device-width, initial-scale=1">            <!-- CSRF Token -->            <meta              proper noun="csrf-token"              content="{{ csrf_token() }}">            <title>{{ config('app.proper noun', 'Laravel') }}</title>            <!-- 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            </caput>            <body>            <div              id="app"              form="flex min-h-screen bg-gray-200">            @yield('content')            </div>            @livewireScripts            </torso>            </html>                  

Brand the components

At present we need to brand a livewire component. Run php artisan make:livewire epitome-upload. This command will create the following files in our project:

app/http/Livewire/ImageUpload.php

resources/views/livewire/image-upload.blade.php

We can render a Livewire component every bit a component on a page. Just since we only have the search component on the page, we are going to utilize Livewire routing.

Supervene upon the code in the routes/web.php file with the following code:

                                    <?php              use              Illuminate\Support\Facades\Route;  Route::livewire('/',              'image-upload');                              

Livewire component design

Now it is time to add together this code to the epitome-upload.bract.php file.

                      <div            class="due west-full            mt-12">            <div            course="container            max-due west-2xl            mx-auto">            @if            (session()->has('message'))            <div            grade="flex            items-centre            px-four            py-iii            mb-6            text-sm            font-bold            text-white            bg-green-500            rounded"            role="alert">            <svg            form="w-4            h-4            mr-2            fill-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            1.957            0            1.305            -1.164            two.512            -2.679            2.512            -i.269            0            -2.009            -.75            -1.974            -1.            99C9.789            1.436            10.67            0            12.432            0zM8.309            20c-1.058            0            -ane.833            -.652            -i.093            -iii.            524l1.214-5.092c.211-.814.246-1.141            0            -1.141            -.317            0            -ane.689            .562            -2.502            one.            117l-.528-.88c2.572-two.186            5.531            -3.467            6.801            -3.467            1.057            0            ane.233            1.273            .705            three.            23l-ane.391            5.            352c-.246.945-.141            one.271            .106            1.271            .317            0            1.357            -.392            2.379            -ane.            207l.6.814C12.098            19.02            9.365            20            viii.309            20z"/></svg>            <p>{{            session('message')            }}</p>            </div>            @endif            <div            class="p-6            mb-12            bg-white            border            rounded-doctor            shadow-40">            <grade            wire:submit.prevent="salve">            <div            class="mb-3">            <input            blazon="file"            wire:model="photo"            form="">            <div>            @error('photo')            <span            class="text-sm            italic            text-red-500">{{            $message            }}</span>@enderror            </div>            <div            wire:loading            wire:target="photo"            course="text-sm            italic            text-grayness-500">Uploading...</div>            </div>            <button            blazon="submit"            class="px-four            py-ii            font-bold            text-white            bg-bluish-500            rounded            hover:bg-blue-700">Salvage            Photo</push button>            </form>            </div>            <div            class="flex            flex-wrap            -mx-two">            @foreach($photos            every bit            $photo)            <div            class="w-1/2            p-2">            <div            grade="w-full            h-total            border">            <img            src="{{            asset('storage/photos/'            .            $photograph->file_name)            }}">            </div>            </div>            @endforeach            </div>            </div>            </div>                  

Nosotros create a simple file upload form. We use wire:submit.foreclose to handle the form submit with Laravel Livewire. We demark Livewire to the file input with wire:model="photograph".

Beneath the file upload form we generate a list of stored photos. Nosotros practise this past looping trough the $photos array.

As well, note that we have a niggling warning at the acme. We will show a message when the prototype is successfully uploaded.

Livewire component logic

Next, we volition add the logic in the ImageUpload.php file.

                                    <?php              namespace              App\Http\Livewire;              use              Livewire\Component;              apply              Livewire\WithFileUploads;              utilise              App\Photo;                              course                ImageUpload                extends                Component              {     apply              WithFileUploads;              public              $photograph;              public                              function                save                ()              {              $this->validate([              'photo'              =>              'image|max:1024',         ]);          $name = md5($this->photo . microtime()).'.'.$this->photo->extension();              $this->photograph->storeAs('photos', $name);          Photograph::create(['file_name'              => $proper noun]);          session()->wink('message',              'The photo is successfully uploaded!');     }              public                              function                render                ()              {              return              view('livewire.image-upload', [              'photos'              => Photo::all(),         ]);     } }                              

First, we validate the submitted file. We check if it is an epitome and that the image is not too large.

Then nosotros create a unique name for the epitome. We exercise this past 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 message that the photo is successfully uploaded to the server.

Linking the storage

If you attempt to upload a file you lot will see that it is non working yet. To brand this all working nosotros must add together a symbolic link to the path where we shop the photos.

Open up config/filesystems.php and add the following lawmaking in the links array.

                      'links'            => [     public_path('storage') => storage_path('app/public'),     public_path('storage/photos') => storage_path('app/photos'), ],                  

Then we run the php artisan storage:link command. This will create the symbolic link.

At present the file uploading system should work. You can upload photos and the photos will display in the list beneath the file upload form.

Wrapping it upwardly

Today nosotros have learned how to utilise Livewire file uploads. You can find the source code on GitHub. If you want to learn more than about Livewire, checkout this tutorial about searching in Livewire.

If yous take any questions, please let me know in the comments. You can also reach out to me on twitter.

boydwitternew.blogspot.com

Source: https://www.larapeak.com/blog/upload-files-and-photos-with-laravel-livewire

0 Response to "Laravel Validation File Upload Doc File Cannot Be Uploaded Liver Server"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel