Laravel 5.8 – From The Ground Up - Laravel 5.8 Tutorial From Scratch – e40 – Image Upload: Cropping & Resizing – Part 2

Education, Programming

Laravel 5.8 – From The Ground Up

52 Lessons

Laravel 5.8 Tutorial From Scratch – e40 – Image Upload: Cropping & Resizing – Part 2

welcome back this is part two of uploading images in laravel in this episode I want to tackle being able to resize our image on the fly and we're

gonna pull in a library to do that and you're gonna see how easy it is however before we get to that I want to show you something right after I uploaded the previous

video one of you pointed out that there is an easier way using the sometimes method to validate our data so I want to show you what that looks like and what we have right now so what we have right

now is we are using this tap method which clearly separates what is always required against what is sometimes required however laravel does have a convenient shortcut for this and if

you're ok with having everything in one single swoop this is what it will actually look like so we can get rid of that altogether and then we can move this line up here and add the key word

sometimes in front of it and we can delete all of this code that does clean up this validate request method very nicely the only thing with this approach is that this image even though is not

always required is clumped together with all of your other fields so if your form is relatively large you're not gonna be able to tell the difference between really truly required fields and those

that require some extra attention but definitely a good call on this refactor I will leave it like this from here on out but either approach will work it's up to you so thank you so much and Tish

for sharing that with us all right let's move on from there so this store image method this is where we need to handle resizing our image like we talked about in the previous episode

anybody can upload any size image into our application but our UI would probably break and that's how it typically is you have a set constraint of what you can do so let me show you

something I want to actually upload a fairly large image and you'll see what happens so I have this new image here it's called happy screen and all it is is just a happy test screen let me pull

that in and save customer so now we have this really wide image then if we changed it again to the test image that we've been using now we have a small image hmm

obviously this would not really work we need to be able to constraint that image so how do we do that well up until this point everything we've talked about ships with laravel we haven't added a

single thing to Lenovo that doesn't come in the box however for image manipulation there is a fantastic library called intervention image which actually handles images

extremely easy so the package site is image that intervention dot IO and here it is so how do we pull in a package we've never really done this before so let's just follow the installation

instructions so first of all we need to use composer now remember composer something we installed in the very first episode so now we need to use it and it will look

something like composer require intervention / image all right let's give that a go let me jump to the terminal and run composer require intervention / image and what this will

do is it will require that package for our project it will add it to the composer that JSON file and then fetch all of the necessary documents and then most packages that are laravel

compatible will automatically register itself with our application to check that you see here in this discovered packages section we have intervention / image a lot of the packages now use that

auto discover feature that was introduced in laravel a little while back so this package has hooked itself up into our application completely automatic so all we need to do now is

use it so how do we use it well to use it we can use something called the facade we're not going to get into facades in this episode but just think of a facade of a way for us to interact

with a class so let's get right to it let's say image equals and then we need to fetch an image class and the image class that we're looking for is this intervention back / image back / facades

and if we use that class then we can call the Mae method on it this method will take our image file and generate a class that has all of the data for the image inside of

it loaded so that we can further manipulate it and then save it again so now before we go on I do want to make extra sure this image is being imported up here at the top and you see it right

here use intervention image façades image if you don't have that it will not work so what do we need to pass to make what the pass to make we have to pass our image

so that way it can create the image now if you remember from the previous episode we created the sim link for inside our public directory storage and then uploads so we can reach into that

file fairly easily let's use a helper function called public underscore path and to that we need to pass in storage so that way would go inside this directory and then we can simply append

our customers' image remember customers image will have the uploads slash and then the name of our file so right after this call we can set I want to fit this image and then it takes two parameters

let's say 300 pixels by 300 pixels and then let's save the image and that's it believe it or not that will take our image it will resize it and save it and put it away in the same place all right

let's give that a go now I'm gonna hit save hit back to Chrome and if you remember when I uploaded that larger image you remember it got kind of large see what happens now and we get an error

image source not readable all right we must have made a mistake and let's see public path okay so storage we need to add a slash because remember that uploads and I

would actually show you this let me die and dump this customer image very quickly just to show you what we have there so you see that uploads doesn't have a slash so we need to be able to

add the slash right after storage so that it finds the correct image all right so with that out of the way let me hit refresh again and there we go so now you see that this image has been fitted

to 300 pixels by 300 pixels let me try the old image that we've been playing with as well so you see the difference save customer and we get the exact same size

so that's pretty cool now don't confuse fit with crop fit and crop are slightly different in that fit will always generate an image that is the exact size that you're asking of it but every

single pixel will be filled with the image as opposed to crop crop we'll take an image but only go as far as it can to fit the image inside so to show you the difference between fit and crop I'm

gonna make a quick change here and I'm gonna make this extremely tall alright so we'll say 300 pixels wide but 1000 tall all right so I'm gonna run the fit first let me run that large image again

safe customer so now of course we have a very tall image and now I will leave that open and let me bring that into a new tab and what I want to do here is resize the same thing but I will change

from fit to crop ok so slightly different method and let me show you the difference with that edit change same image save customer and here you go so that's the difference you see that this

image has filled everything and cropped everything out that it didn't need as opposed to this image where you create these black lines on top and bottom because the image is actually not tall

enough to fit inside a 1000 pixel tall image so that's the difference this is fit and this is crop so that's pretty cool now if you want to learn a little bit more about the intervention image

you can see the API right here so we've been using fit so this is the fit and of course we just looked at crop so one cool thing about crop and fit is that they do have options so there's other

things here that you can pass it for example in fit we can determine what position we want the image to get fitted to of course Center has been the default but you may prefer top left so let me

show you how to do that very quickly let's change from crop back to fit and we'll say 300 by 300 again as a third parameter I'll pass no but as a fourth parameter

let's pass a string and let's pick one of these top left seems easy enough so top left hit safe go back here and let's change our image one more time happy screen so now our image is being

captured from the top left so as you can tell there's many different options that you can pass him and a lot of the times Center is typically what you would want you just want the center part of the

image but now you know how to be able to resize and save an image on the fly using this intervention image package great so let's just do a quick recap of everything we touched on so this is the

new refactored validate request using this sometimes validation that we haven't seen up until this point and that was as an aside obviously that's a little bit of trailing from previous

episode in this episode we mostly took a look at these two lines right here so the first thing we did was we pulled in our intervention image package using composer required and then we noticed

that it discovered itself and completely hooked itself up into our application automatically so that's pretty cool then we use the image facade which we are importing up here under intervention

image façades image and we are using it down here to make an image using our public path and then we're fitting that image to a square of 300 pixels by 300 pixels and then as an extra credit we

did change the positioning that it used to do the cropping and then finally we just hit the safe method now as a quick note on the safe method we use the safe method with no parameters you can pass

in a parameter in here if you wanted to save it to a separate place effectively doing a save as as opposed to just a safe if you just hit save it will go back and overwrite the original image so

just remember with this method unless you save it to a different place you are overriding the original image that got uploaded by the user so that is it for this episode this is a very highly

requested feature that a lot of apps will need and levo with the intervention package makes it extremely easy to handle so as always leave any comments or questions down below in the comments

don't forget to subscribe and when you're ready I'll see you in the next episode

In part 2, let’s handle resizing our image to fit inside a 300 by 300 pixel square. Then explore other options for cropping and resizing.

For the best experience, follow along in our interactive school at https://www.coderstape.com

Intervention Image Package
http://image.intervention.io/

DigitalOcean Referral
https://m.do.co/c/7dce5364ef4d

Resources
Course Source Code
https://github.com/coderstape/laravel-58-from-scratch

Hit us up on Twitter with any questions or comments @codertape (https://twitter.com/CodersTape)

About This Course

Ready to get started on your path to Laravel Artisan? In this series, we are breaking down all of the basics of Laravel to get you comfortable using the world’s most popular PHP framework. Let’s get started!

    add to database laravel admin laravel artisan Artisan Command artisan commend create artisan console artisan laravel command authentication in laravel belongsto belongsto laravel example coding tutorials create artisan command create command artisan create new command artisan Create your own crud laravel crud laravel tutorial crud resource laravel crud with file upload custom artisan commands custom artisan commands laravel custom laravel database configuration laravel database relationship digital ocean dotenv eager loading eager loading in laravel eager loading vs lazy loading laravel eloquent eloquent accessors eloquent mutators eloquent orm feature testing laravel fetching data in laravel filesystem laravel form requests full stack vue gate and policy laravel google optimize hasmany hasmany laravel hasmany laravel example hasmany relationship in laravel hasone hasone relationship in laravel How to create how to queue email how to use queue installing laravel intervention image laravel laravel 5 laravel 5 auth laravel 5.4 queue laravel 5.5 queue laravel 5.8 laravel 5.8 artisan command laravel 5.8 artisan console laravel 5.8 auth tutorial laravel 5.8 authentication laravel 5.8 commands laravel 5.8 crud laravel 5.8 crud example laravel 5.8 custom middleware laravel 5.8 deprecations laravel 5.8 eager loading laravel 5.8 elixir laravel 5.8 event listeners laravel 5.8 events laravel 5.8 feature laravel 5.8 features laravel 5.8 global middleware laravel 5.8 install laravel 5.8 lazy loading laravel 5.8 listeners laravel 5.8 middleware laravel 5.8 multi auth laravel 5.8 named resource routes laravel 5.8 named routes laravel 5.8 new feature laravel 5.8 own artisan command laravel 5.8 queue laravel 5.8 queues laravel 5.8 routing laravel 5.8 telescope laravel 5.8 tutorial laravel 5.8 user auth laravel 5.8 user authentication laravel 5.8 what's new laravel 5.9 laravel admin permissions laravel api laravel artisan command laravel artisan console laravel assets laravel auth laravel auth role laravel authentication laravel authorization laravel axios post example laravel background process laravel background task laravel background worker laravel beginner to master laravel belongsto laravel belongsto vs hasone laravel belongstomany laravel best packages laravel best practices laravel best tutorial laravel bootstrap laravel command laravel command line laravel commands tutorial laravel composer install laravel connect db laravel console command laravel console testing laravel contact form send email laravel controllers laravel create laravel crud laravel crud policy laravel custom command laravel custom middleware laravel database laravel database configuration laravel database relationships laravel database seeder laravel database settings laravel db seed laravel db settings laravel debugging laravel deploy aws laravel deploy digital ocean laravel deploy on digitalocean laravel deploy on server laravel deploy to production laravel deployment laravel digitalocean laravel drag and drop file upload laravel dropzone file upload laravel dropzone image upload laravel e-commerce laravel eager loading laravel eager loading tutorial laravel eager loading with condition laravel elixir laravel eloquent laravel eloquent belongsto laravel eloquent crud laravel eloquent hasmany laravel eloquent where laravel eloquest tutorial laravel events and queue laravel events tutorial laravel factory laravel feature test laravel feature testing laravel fetching data from database laravel file storage laravel fillable example laravel flash message notification laravel for beginners laravel form validation laravel forms laravel forms bootstrap snippets laravel from scratch laravel from the ground up laravel front end laravel frontend tutorial laravel gate and policy tutorial laravel global middleware laravel hasmany laravel hasone laravel i18n laravel installation laravel installation mac laravel intervention image tutorial laravel javascript tutorial laravel jobs queue laravel language laravel language switcher laravel language tutorial laravel languages laravel lazy loading laravel listener event laravel listeners laravel localization laravel login laravel mailable tutorial laravel many to many relationship example laravel markdown email laravel markdown mail laravel mass assignment laravel middleware laravel migrate fresh laravel mix laravel mix 5.8 laravel mix vue laravel model factory tutorial laravel multiple language laravel mysql json laravel named resource routes laravel named routes laravel new features laravel news laravel nginx laravel node modules laravel npm install laravel npm run watch error laravel one to one laravel paginate laravel paginate link laravel pagination laravel pagination 5.8 laravel pagination links laravel pagination tutorial laravel phpunit laravel phpunit testing laravel pivot table example laravel policy laravel preview laravel query optimization laravel queue laravel queue event listener laravel react laravel register user laravel registration laravel registration validation laravel relationships laravel reset password laravel role middleware laravel role permission laravel roles laravel route group middleware laravel routes laravel routing laravel routing with parameters laravel sass laravel save file to database laravel scopes laravel seo tutorial laravel server laravel session data laravel ssl laravel supervisor laravel tailwind css laravel tailwind setup laravel tdd laravel tdd tutorial laravel telescope laravel telescope installation laravel telescope tutorial laravel test driven development laravel test workflow laravel testing laravel testing controllers laravel testing tutorial laravel tools laravel translation laravel tutorial laravel tutorial for beginners laravel ubuntu server laravel ubuntu tutorial laravel unit testing controllers laravel upload file laravel upload image to storage laravel upload multiple files at once laravel upload multiple image to database laravel upload multiple images laravel url slug laravel vue laravel vue js crud laravel vue setup laravel vue tutorial laravel vue.js laravel webpack error laravel webpack tutorial lazy loading lazy loading laravel lazy loading vs eager loading learn laravel learn laravel framework step by step localization in laravel localization laravel many to many laravel mvc tutorial for beginners in php mvc tutorial laravel mysql mysql relational database mysql relationship n + 1 problem n + 1 problem laravel new artisan command npm install npm run dev npm run watch laravel one to many one to one one to one laravel own artisan command pagination pagination bootstrap pagination bootstrap php mysql pagination laravel pagination laravel bootstrap pagination links pagination php php php artisan php carbon immutable php framework php framework 2019 php what's new 2019 phpunit phpunit laravel phpunit testing pivot laravel policy laravel polymorphic relationships queue and events queue email queue for laravel queue jobs queue laravel 5.8 registration form relationship laravel eloquent relationship mysql restful controller role permission in laravel roles laravel route model binding laravel routing in laravel save image to database seo friendly seo friendly content writing seo friendly website seo laravel seo optimization simple pagination laravel slugify sqlite relational database sqlite relationships between tables symfony command console symfony laravel tailwind css tailwind laravel mix telescope laravel tutorial laravel unit testing unit testing laravel upload file laravel upload file php upload image laravel upload image to database php upload images laravel upload multiple files in php url slug laravel url slug php vue vue.js vuejs laravel why use laravel queue why use queue