Laravel 5.8 – From The Ground Up - Laravel 5.8 Tutorial From Scratch – e15 – Eloquent Accessors & RESTful Controller – Part 1

Education, Programming

Laravel 5.8 – From The Ground Up

52 Lessons

Laravel 5.8 Tutorial From Scratch – e15 – Eloquent Accessors & RESTful Controller – Part 1

we've made some great progress with our customers lists we're able to have companies were able to associate our customers to companies and were able to

retrieve the relationship between customers and companies I want to spend some time refactoring this view to a more traditional form for creating customers and then having a view to be

able to view all of my customers as opposed to this mixed view where we have a form at the top on our customers at the bottom and through all of that we're gonna learn some more Lenovo basics so

let's get right to it so the first topic is restful controller's restful means that as follows a particular pattern of method names to actions and when you follow

this pattern it ensures that your controllers stay nice clean and short and overall improves your code dramatically so I want to show you this in the documentation first and then

we're going to start digging through our code and refactoring some of it to follow this convention so let's visit the level Docs right now let's go to Larry Volcom / Docs and here we are and

then if we do a search here at the top and say controllers and resource controllers that's what we're looking for and we scroll down here just a little bit here we are so these are the

actions there are seven of them in total and this is the pattern that you will follow here's the verb here's what the URI would look for and then you look at the action meaning the name of the

method in the controller and then the route name now the route name only applies if you use a resource in your web browser file which we have not talked about yet so go ahead and ignore

the routes name just for now so we have these seven methods here let's take a look at the first one if we said an index an index sounds a lot like we've been calling a list check it out

if we go to our customers controller so this list method here is basically the index method because the index method what it does is it basically gives you a list of the entire resource so let's

refactor that now so instead of list needs to be called index and then let's visit our web browser file and change this from list to index all right let's hit refresh and of course it's still

working however if you really looked at this and you look down at the second one the second one should be something like customers slash creates and the create

is what will contain the form that we have so we need to split this off because right now this top section is our create view so let's take care of that now

now before we create that I do want to do one more change here and it's this views our current view directory structure is to have these internals and then dot customers but I find that a lot

easier if you follow the exact same convention so instead of internals I'm gonna say customers because that's the name of our controller and instead of customers I'm gonna say index that way

it follows the exact same convention so let's go into resources views and let's change that now I'm gonna make a new directory first we're gonna refactor this in steps so follow along directory

we'll say this is gonna be customers and you could do uppercase you could do all lowercase there's no real convention on this I'm gonna stick to all lowercase but you could do a capital C if you like

so in my customers I need what we are now calling internals customers so I obviously need to move that into my customers now and I need to rename that so let's rename that refactor rename and

this is going to be called index okay we can actually get rid of this internal directory we're no longer using it so let's get rid of it delete ok so now we need to change this this is no longer

internals customer this is customers dot index so that follows the same convention customers index inside the customers controller in the index method that makes sense alright so now let's

start talking about this create method so we know we're going to need a public function called create and create simply going to return a view of some sort of course and the view as you may have

guessed is customer dot create so let's create that view now we'll say new file create that blade that PHP and what needs to go in here is basically just the top half of what

we've been calling index so I'm gonna actually copy the whole thing and we'll bring it in here and let's edit it from here on down this is basically our index so we can get rid of that and so we have

our form and let's change the title to add new customer makes a little bit more sense let's change the title to add new customer as well and I think we're good on that one now on the index we can get

rid of the form altogether and we can get rid of that and what we need to do is of course we need to add a link so I'll just add it here for now we'll say a P tag anchor tag and where is this

gonna go well this is gonna go to customers create and we don't have a web route for that just yet but we'll take care of that in just a couple of seconds so add new customer let's take care of

that route customers index let's create a new one customers slash creates and this goes to the creates method now just to recap back in the documentation this is what we're trying to achieve we're

trying to have this create action meaning a method with the name of creates and we want to route it using a URL that has the resource name in the case of the documentation they're using

photos as the example in our case is customers so we'll have slash customers slash creates and it's gonna be a get method so we have our get method and it's going to be customers slash creates

and we have our customers controller with our creates alright let's see if that refactor was successful alright so I hit refresh I have my index which we're gonna work on in just a couple of

seconds but if I hit add new customer it says undefined variables companies ok we missed something let's go back to our controller and sure enough if we go back to our view it depends on companies to

be able to give us a list of companies to choose from so we forgot to bring that over so I'm going to bring this line into this method just moving that and of course we don't have to compact

companies anymore and so here we'll say compact companies and let's give that another go aha there we go let's try to add a customer now new customer some email active add

customer and it did redirect us as you notice here we went to customers slash customers so we can no longer simply return back from our store method because if we do then of course we'd end

up in a nested resource of some sort so let's actually return a redirect and we're gonna redirect back to customers alright let's see what's going on here if we go back to customers ah it looks

like companies is a dependency that it needed let's see why that is let's go to my index view that's right so we have this for each company we had added this just to prove that we could have the

relationship in the reverse order I'm going to tackle the companies as a separate controller all together so I will delete that code which leaves us just the add customers and then we'll

have these two columns the active and inactive let's see what we get now so if we took a look at our create method so our form action up until this point I've been using this customers right but now

that we're inside a customers slash creates that's why it's redirecting us to the wrong place so I actually just need to put a slash in front of customers and that should fix it for us

let me go ahead and hit refresh on this page and let's add our new customer now so new customer email ID email com add customer and there we go so we are working again but now we have our create

method which is helping us to keep our controller in check and here it is here's our create method nice and simple two lines and now we have our index method which we're going to work on in

just a second and then we have our store method so let's get back to this index so I no longer want to have this active customers and inactive customers so I will actually revert back to just having

customers equals app customer and let's just fetch all of them at this point let's get rid of these two lines let's get rid of this all together it'll just be customers from here on out and get

rid of that all right let me go back to the index view what I want to do is a more traditional table style for my customers so we'll do this the bootstrap way so let me actually wrap this inside

for each customers ass customer and hopefully this flow is starting to get a little easier to understand and follow as we're doing it and that's the beauty of this I'm gonna do this over and over

until it kind of clicks in so just keep following along as I'll repeat this over and over and you'll see the process how it evolves and it starts to make sense we'll have a row for each of my

customers and the first thing I want to do is maybe have a column of two and inside there we'll have the customer ID and then let's get rid of all this I don't need any of that so we'll get rid

of that our customer ID then let's have the customers name will say that is customer name and then let's have the customers company name so customer remember we're gonna fetch the

relationship company no parenthesis name so we got their company name and then so we have two plus four plus four we need two more so let's do two more and maybe we'll call this the active just to see

if they are active or not all right let's check it out on a browser and see if we made any mistakes back to my customer list looks like we have sort of the same error in our navigation let's

go back and fix that as well so navigation yep it needs to be slash about a slash contact and slash customers all right so let's go back refresh

customer list there we go so we have our customers we have their ID their name and their company and then we have this one and zero which we obviously know represents active or inactive I'm gonna

show you a really cool trick and I remember learning this when I first started in level and I was so excited about it hopefully you find this as useful as I did so if we want to convert

this one to an action your typical approach may be to say something like alright so if my customer is active right and we could do a shorthand notation on this we can say well if it

equals to one then that means it's active and if it equals to zero then that means it's inactive okay would that work it sure would that works a hundred percent but if you have more

than two statuses that breaks down right away it works good if it's just active and an inactive when you have active in progress and other things and other labels for other statuses it just

doesn't work so I'm gonna revert that that's not how we're going to do it so how we're actually gonna do it is we're gonna be using the model to do it so let's go to my customer model and here's

the trick level has a feature called accessors and mutators and accessors and mutators will allow us to interject any call that we want and do something to it before it either displays it on a page

or saves it back into the database so let me show you what I mean I'm going to add a new method here and a lot like the scope this is going to be worded in a very specific way so that it works so to

make an accessor it's get and then the column name so in our case it's active so get active and then attribute so get active attribute so this is going to give us the attribute as a parameter and

what I can do here is I can actually generate through an array and figure out which one it is let's do it all in line so we'll do a big return statement and we'll say it's going to be an array and

my array is going to say if it's zero we know that means inactive and if it equals one then we know it is active and then through the magic of PHP we can actually call attribute on that so that

will return the proper attribute for us and to prove it I'm gonna comment this out right now hit save go back refresh and you see we're back to 1 0 1 1 and then let's go ahead and

save that again and there we are so we now have a singular place where active becomes 1 and inactive becomes 0 and it is inside our model and that makes sense because

the model remember is the one that's in charge of a customer so this class if you want to know anything about our customer this is the class where it goes instead of having to repeat that over

and over every single time we have to use this active column from here on out it will always output inactive and active instead of 0 and 1 just to check that everything's still working let's go

ahead and add a new customer and obviously we still have our active and inactive column so let's do another person funky email had customer and there we are we're still getting active

and inactive and everything is working again we're following those restful verbs that we found here in the documentation obviously the store method would be the

next in line in the store method we actually already implemented the right way so I'll just review it so here it is we have a store method and the store method redirects back to our index

method right now generally speaking a store method redirects back to the show method which is the one that actually shows you the newly made resource and that makes a little bit of sense if you

added a new customer you probably want to be redirected to that customers detail page and not the index of all of your customers so we'll work on getting a show view for our customers in the

next lesson but let's just wrap up the store method by going to the web routes and we see that we have a route with a method of post to customers and it's going to a store method and of course

here it is it follows the convention post and is routing to just the base name of your resource and is using an action of door so the one that we're going to

handle next is this one here this show method so stick around in the next episode we're gonna handle the show view

It’s time for us to tackle a refactor of our controllers and views to implement a RESTful controller approach. Follow along as we implement the index, create and store methods in our controller and properly store our views, following the same approach. As a last bit, let’s write an accessor for our active column for better display.

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

Resources
Course Source Code
https://github.com/coderstape/laravel-58-from-scratch
https://laravel.com/docs/5.0/controllers#restful-resource-controllers

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