banner



How To Make A Form With Upload Image Code

Today, I will testify y'all guys how to add Laravel Epitome Upload functionality into your application with validation. This one will be a step by step guide, by the end of this post y'all will familiarize how to upload an image in Laravel.

Uploading the image in Laravel is very easy! So if you lot are beginners and so you can do that simply. Laravel provides a very uncomplicated way to create file uploading with proper validation like max file size 2mb, file extension should be jpeg, png, jpg, gif or SVG etc.

In this postal service, I volition walk you lot through how nosotros tin can add the profile image to Laravel's default authentication which comes out of the box.

Past the end of this post, yous will have a working example like below.

Laravel Image Upload Made Easy
Laravel Epitome Upload Made Easy

So let'south commencement.

Application Setup

I assume, you already have fresh Laravel project, if non go and create with below command.

composer create-project laravel/laravel LaravelImageUpload

At present, open up .env file which is located int the root of your LaravelImageUpload project folder. Update the database credentials with your ones.

Once yous have connected a database to Laravel, run beneath control to generate default Laravel'due south hallmark scaffolding.

php artisan make:auth

In one case you take generated the scaffold, we are ready to start.

Updating Migration File

Laravel provides you lot a User model and migration for this model by default. Go to database/migrations folder and open 2014_10_12_000000_create_users_table file.

We will be uploading a contour image for currently authenticated user, so we demand to add together an extra field in which nosotros will store the prototype file path. Update the upwardly() method with below one:

public part up()     {         Schema::create('users', function (Blueprint $table) {             $table->increments('id');             $tabular array->string('proper name');             $tabular array->cord('electronic mail')->unique();             $tabular array->string('profile_image')->nullable(); // our profile image field             $tabular array->timestamp('email_verified_at')->nullable();             $table->string('password');             $table->rememberToken();             $table->timestamps();         });     }

As you take noticed that, we have added a new field chosen profile_image and set its type to string. Notice that we have added a nullable() flag to new fields to keep this epitome uploading optional for users.

Once you have updated your migration, run below control to create all your migrations.

php artisan migrate

Now if you lot, cheque your database you volition be able to come across that Laravel will create two tables chosen users and password_resets.

Now it'south time to update our User mode. Open app/User.php file and add profile_image to $fillable assortment.

protected $fillable = ['name', 'electronic mail', 'countersign', 'profile_image'];

Also nosotros will add a new accessor method to become the user'due south profile image like and then auth()->user()->image instead of using profile_image field. Then add beneath code within User course.

public function getImageAttribute() {    return $this->profile_image; }

Contour Routes

After migrating tables and updating User model, now nosotros need to setup a new page with form where we will exist able to upload image. So for that create two routes in your web.php routes file. Like and then:

Route::become('/contour', '[email protected]')->name('contour'); Route::mail('/contour/update', '[email protected]')->name('profile.update');

Profile Controller

As yous have noticed that we accept used ProfileController in above routes, so run below command to create a new controller.

php artisan make:controller ProfileController

At present open your newly created controller and update with below lawmaking:

namespace App\Http\Controllers;  employ Illuminate\Http\Request;  course ProfileController extends Controller {     public role __construct()     {         $this->middleware('auth');     }      public role index()     {         return view('auth.profile');     } }

As you accept seen in the __construct() method we take gear up the middleware so only authenticated users will be able to update their profile.

In alphabetize() method we are merely loading a new view called contour which is residing inside auth folder generated past Laravel.

Profile Blade Templates

To a higher place code example is merely bootstrap template with a course to upload an image. In form'south action we accept added {{ route('profile.update') }} route, and so when we will submit this class information technology will striking that route.

Notation that we have added enctype in the form declaration which very of import for uploading files. Without this your class volition not upload whatever file.

Next, we have a input field for user proper name and loading information technology's electric current value using hallmark helper like this auth()->user()->proper name.

Adjacent, we have a input field for user email and loading its value in value aspect. I'm keeping this field disabled and so that electronic mail modify is not possible.

At present, we need to add a drop-downward menu for the currently authenticated user to access the profile page. For that in your resources/views/layouts/app.blade.php file add below line of code just before the Logout dropdown item.

<a class="dropdown-item" href="{{ route('contour') }}">Profile</a>

Now if yous click on the Profile link it will load the below view.

Profile Page
Contour Page

Configuring FileSystem for Storage

Afterwards finishing our view templates modification, at present we demand to configure our file system where we will be uploading images. Get to config/filesystem.php file and change the settings for public disk with below.

'public' => [             'commuter' => 'local',             'root' => public_path(),             'url' => env('APP_URL').'/public',             'visibility' => 'public',         ],

Image Upload Trait

You can handle the image uploading logic within your controller, merely I would like to separate this logic into a trait which we can use later on if we need to upload images.

In your app folder, create folder called Traits and add a php file chosen UploadTrait.php. Add below code snippet in it.

namespace App\Traits;  apply Illuminate\Support\Str; use Illuminate\Http\UploadedFile; use Illuminate\Back up\Facades\Storage;  trait UploadTrait {     public role uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = zippo)     {         $name = !is_null($filename) ? $filename : Str::random(25);          $file = $uploadedFile->storeAs($folder, $name.'.'.$uploadedFile->getClientOriginalExtension(), $deejay);          return $file;     } }

In the higher up code example, we are creating a new function called uploadOne which volition handle the file uploading by taking the uploaded image, folder, disk, and filename parameters.

Firstly, we are checking if a filename has been passed, if not then we are creating a random string name.

Next we are uploading the file using UploadedFile's storeAs method and returning the file we just stored. Null fancy.

Processing Image Upload in Profile Controller

After setting upwards the filesystem and creating a trait, it'southward the time now to use the trait in our ProfileController for treatment the form submission. Every bit we already have created a route which will hit the updateProfile method. So let's add that method. Use the below code example, and supercede your current ProfileController with this i.

namespace App\Http\Controllers;  utilise App\User; use Illuminate\Http\Request; use App\Traits\UploadTrait;  class ProfileController extends Controller {     use UploadTrait;      public function __construct()     {         $this->middleware('auth');     }      public function index()     {         return view('auth.contour');     }      public part updateProfile(Request $request)     {         // Form validation         $request->validate([             'proper noun'              =>  'required',             'profile_image'     =>  'required|image|mimes:jpeg,png,jpg,gif|max:2048'         ]);          // Get current user         $user = User::findOrFail(auth()->user()->id);         // Ready user name         $user->name = $request->input('proper noun');          // Check if a profile image has been uploaded         if ($request->has('profile_image')) {             // Get paradigm file             $prototype = $request->file('profile_image');             // Brand a image name based on user name and current timestamp             $name = Str::slug($request->input('proper noun')).'_'.time();             // Ascertain binder path             $folder = '/uploads/images/';             // Make a file path where prototype will exist stored [ folder path + file name + file extension]             $filePath = $folder . $name. '.' . $epitome->getClientOriginalExtension();             // Upload image             $this->uploadOne($image, $folder, 'public', $name);             // Set up user profile paradigm path in database to filePath             $user->profile_image = $filePath;         }         // Persist user record to database         $user->save();          // Render user back and show a wink message         render redirect()->back()->with(['status' => 'Profile updated successfully.']);     } }

Above code is self-explained, we take injected our trait into this controller and added a updateProfile method.

Get thorugh the updateProfile method and read the comments to follow forth. I have added enough comments to explicate every single line.

After updating the ProfileController, if you now go to the profile page and submit an epitome it should be working every bit expected. Try to upload a wrong file blazon and yous will get the validation errors displayed equally well like beneath.

Image Upload Validation
Epitome Upload Validation
Image Upload Validation
Prototype Upload Validation

Adding Profile Image to Dropdown Menu

Past now you should have a fully functional prototype upload profile section. One last thing nosotros need to show the currently uploaded image next to the username in header similar in the demo prototype. For that in your app.blade.php layout file, replace this:

<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" 5-pre>         {{ Auth::user()->proper name }} <span class="caret"></span>     </a>

with this:

<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="fake" v-pre>         @if (auth()->user()->image)             <img src="{{ nugget(auth()->user()->image) }}" style="width: 40px; height: 40px; border-radius: 50%;">         @endif         {{ Auth::user()->name }} <bridge class="caret"></span>     </a>

Now if you lot upload an epitome once more, you will be able to see the uploaded image before the user name.

Not bad! nosotros have successfully created a profile update department with Laravel Image Upload. You lot can discover the Source Code of the to a higher place instance on Github.

If you have any question or proffer to improve this postal service, please allow me know in the comments box below.

Source: https://www.larashout.com/laravel-image-upload-made-easy

Posted by: overbeyeaspost.blogspot.com

0 Response to "How To Make A Form With Upload Image Code"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel