The Laravel Survival Guide Tony Lea
User Manual:
Open the PDF directly: View PDF .
Page Count: 98
Download | |
Open PDF In Browser | View PDF |
The Laravel Survival Guide Tony Lea © 2015 - 2016 Tony Lea Table of Contents Thanks Introduction Chapter 1 - Getting Started Chapter 2 - Composer & The Laravel Installer Chapter 3 - The Laravel Structure Chapter 4 - Routing Chapter 5 - Models Chapter 6 - Model Relationships Chapter 7 - Mutators Chapter 8 - Views Chapter 9 - Blade Chapter 10 - Controllers Chapter 11 - Piecing It Together Chapter 12 - Artisan Chapter 13 - Middleware Chapter 14 - Authentication Chapter 15 - Requests Chapter 16 - Responses Chapter 17 - Migrations Chapter 18 - Seeds Chapter 19 - Security Chapter 20 - Testing Chapter 21 - Wrapping Up Thanks I want to give a special thanks to my family for always being supportive. I especially want to thank my wife for being an amazing woman and for pushing me to try and be the best person I can be. This book would not be possible without the love and support of my amazing family. Additionally, I want to thank to David Cullinan for helping out with book. Ok, enough with all the thanks. Let’s start learning Laravel! Introduction Why The Book? Well, it’s not really a book… It’s more of a guide (hence the title). A guide to save yourself and others from becoming a zombie developer! What exactly is a zombie developer? Well, a zombie developer is a developer like you or I, yet they mindlessly hack on PHP apps and do the same thing over and over. These repetitive tasks are incredibly time consuming, and make the developer brain dead. When this happens it gives them a thirst for blood and an urge to kill. So, instead of letting this happen the developer could have used the amazing Laravel framework for rapid application development. This will help them keep their sanity and it will make coding enjoyable again. Oh, yeah… And it’ll save lives. By learning the basics of Laravel you can save yourself, and possibly others, from becoming a deteriorating zombie developer. Don’t let that inner zombie revive, be sure to keep in hand this Laravel survival guide. Chapter 1 - Getting Started A zombie developer is very slow at setting up a new project, whereas a Laravel developer can run a few commands to set up a new project in a matter of seconds! Being aware of one’s environment is crucial to surviving the zombie developer apocalypse. In this chapter, we will briefly go over setting up your local environment. Quick note: We will not go into full detail of installing system requirements such as PHP, MySQL, and Apache. Instead, we are just going to give a quick overview on setting up your local development environment so that way we can start getting into the code as soon as possible. Your Local Development Environment A local environment, also referred to as the “development environment”, is when you work on your web app from your computer. When you are ready to make your application available for the world to see you will move your code to another server referred to as the “production environment”. So, when we set up your local development environment we are referring to setting up the required applications to run a Laravel app on your computer. A basic local development environment for Laravel typically requires 3 applications, which are: 1. Apache or Nginx (the web server for your application) 2. MySQL (the database for your application) 3. PHP (the server-side scripting language for your application) There are many programs for each operating system that will install all these applications for you. Just to name a few there is MAMP, WampServer, and XAMPP. You can feel free to check out the links below for these applications: https://www.mamp.info/en/ (Mac and Windows) http://www.wampserver.com/en/ (Windows) https://www.apachefriends.org/ (Mac, Windows, and Linux) Be sure to read the docs for all the system requirements at http://laravel.com/docs. There is also one last way of getting your local development environment setup for Laravel that is well worth mentioning. It is called a virtual machine that has all the system requirements already installed. You can learn more about setting up a Laravel virtual machine at http://laravel.com/docs/homestead. There is no right or wrong way to setup your local development environment as long as you meet the minimum system requirements for Laravel. Find a way that works for you and start building the next latest and greatest web app! Okay, Let’s move on to Composer and the Laravel Installer. Chapter 2 - Composer & The Laravel Installer A zombie developer manually moves files into their project, whereas a Laravel developer leverages composer to install tools and libraries. Taking on the zombie developer apocalypse on your own would be almost impossible. Getting help from others is essential, and that’s exactly what composer allows us to do. Composer is used to include libraries from other developers into our application. Let’s continue. Composer & The Laravel Installer How easy would it be if you could open up a command prompt and type in: $ And a Laravel app is created inside a folder named “blog”. Well, that’s what the laravel installer does. So, let’s learn how we can use this on our computer. The Laravel installer, as well as many PHP packages, make use of a dependency manager called Composer (http://getcomposer.org) to add this functionality. So, What exactly is a dependency manager? Well, a dependency manager is nothing more than a tool to manage your dependencies. “WHAT!!!?”, yeah the definition still sounds pretty abstract, right? Let me put this another way to help you understand how Composer works. I know you are probably a fan of eating pizza instead of eating brains, so let’s pretend we could use a command to make us a pizza: $ By default, we are given a pepperoni pizza. But let’s say we wanted this command to make us a pizza with different toppings. Perhaps we wanted a meat-lovers pizza. We would probably need the following toppings: { "toppings" : [ "peperoni", "ham", "bacon", "beef", "sausage" ] } Now, if we save this file in our current directory and name it ‘composer.json’ and run the command again: $ DING! We now get our meat-lovers pizza instead of our pepperoni pizza. Hazzzaa! As you can see Composer is a way of managing the things we need to build our app (or pizza). Composer is also a command line tool we can use it to install other command line tools. One of those tools is the Laravel installer. To add the Laravel installer to our computer, we must first install composer. Visit https://getcomposer.org/, click on the ‘Getting Started’ button, navigate to ‘Installing Globally’, and walk through how to globally install composer on your machine. After downloading and installing composer you can run the following command to add the Laravel installer. $ "laravel/installer=~1.1" Now we have successfully added the laravel installer to your machine, and you can easily create a new laravel app by typing: $ Then navigate to your new app_name folder in a command prompt. And run: $ Finally, navigate to http://localhost:8000/ in your browser and you will see a ‘Welcome to Laravel’ screen. Now you’re ready to start building your amazing app! Warning: If the laravel installer does not globally work you may need to specify where the composer bin directory is located on your machine. Visit http://devdojo.com/post/composer-bin-directory-path to learn how to do this. How awesome is this? With a single command line, you can be up and running with a new Laravel app in a few seconds! You can learn more about the Laravel installer at http://laravel.com/docs. Chapter 3 - The Laravel Structure A zombie developer puts files all over the place causing an unstable structure, whereas a Laravel developer keeps their structure clean and consistent. A solid structure is essential for making your app efficient and awesome. Zombie developers are used to ruins and destruction, but as a new Laravel developer, you will get accustomed to a solid foundation and structure. In this chapter, we are going to give you a brief overview of the Laravel file structure. The Laravel Structure In a new laravel project you will have the following code structure: You will see nine folders which are: 1. 2. 3. 4. 5. 6. 7. 8. 9. app bootstrap config database public resources storage tests vendor I’m not going to go into detail with all the files; however, I will give you a brief rundown of each folder. App This is the directory that has all our application logic. In this folder, we will put all our models, controllers, services, and many other classes. Bootstrap This folder is used to bootstrap laravel (startup laravel). Config This file will contain many of our global configurations for our application. Database This folder contains our database files such as migrations and seeds. Public This public folder contains many of the applications assets such as images, stylesheets, and scripts. Resources We will put our view files in this folder. The views are the pages that a user sees. Storage Laravel uses this folder to store sessions, caches, and logs in this folder. Test This folder contains files that we use to test the logic of our application. Vendor This is the folder that contains our dependencies. When you add new libraries (toppings) to your app, this is the folder that will contain those libraries. Do you recognize the composer.json file from the image above? Remember this is where we define our dependencies (pizza toppings) for our app. One important file worth mentioning is a file called .env; this is the file that contains configurations such as debug mode and database credentials. So, when you need to connect a database to your Laravel app you will need to update the following code in that file: 1 2 3 4 You will replace the database name, username, and password accordingly based on your credentials. Add your database credentials to these variables and it will be available for your app to use. Finally, there is one particular file that I want to point out. The routes.php file, which is located in app/Http/routes.php. This is the file that we will add all of the routes for our application, and this is what we are going to cover in the next chapter. So, Let’s move onto some fun stuff! Chapter 4 - Routing A zombie developer reinvents the wheel and creates their own routing system, whereas a Laravel developer leverages the built-in router that is simple to use, extremely flexible, and super efficient. Using a powerful routing system in your app is crucial for keeping your sanity and preventing brain deterioration. When a user navigates your app they won’t run into a dead end; they’ll hit the correct “route” instead. Routing overview Just to be sure everyone is on the same page, we’ll give you a brief run down of app routing. You can think of a route as being similar to a road. For instance, “We drove down the road (route) to the graveyard.” When referring to routes in an application, it is essentially the same. When you type a website URL like site.com/graveyard, you are telling the browser that the graveyard is the route you want to take. The application then says, “Ok, you want to go to the ‘graveyard’? This is the output I have for the graveyard route.” This can be done very easily using Laravel, for instance: 1 2 3 4 When the user submits the form in the code above the data inside the form will be posted to the site.com/zombie POST route. How about the PUT and DELETE method? Well, the next 2 methods will need to have a hidden input type to specify that it is a PUT or a DELETE. For example: 1 2 3 4 5 6 7 8 9 10 11 12 13In the previous code sample the forms will send data to the PUT & DELETE route respectively. Quick Routing example Let’s go through a quick route example of how we might destroy a zombie! First we need to have a form where we can delete a zombie. Let’s say that we have the following code in one of our views: 1 The view above will show a button titled ‘Destroy’. For simplicity purposes we are just hard-coding an input with an ID of 2, but normally this would change based on the ID of the zombie you actually want to delete. Next we need to create our route that will delete that zombie: 1 2 3 4 5 6 7 8 input('id'); Zombie::destroy($id); }); And just like that we have destroyed the zombie with an ID of 2 :) Pretty cool! Additionally, notice that we specified a Request variable in the function above. This is simply a class provided by Laravel that allows us to capture request information. But, before we can use the Request class we have to specify the namespace: 1 Quick Note: Unfortunately, the above example will not fully work since we have not setup our database or models just yet, but we will do that in the next chapter. In the above route examples, we are using route closures. Let’s move on to talk about route closures vs route controllers. Route Closures vs Route Controller Actions A route closure is when we specify a route, and we run a function containing code. This is a route closure: 1 name . '
'; 6 echo 'Strength: ' . $zombie->strength . '
'; 7 echo 'Health: ' . $zombie->health . '
'; 8 }); Above we are getting the zombie with an ID 5 and we are displaying their name, strength, and their health level. The example above will not entirely work since we have not set up our Models or our database yet. So, with that being said let’s move on to talk about our model classes. Chapter 5 - Models A zombie developer creates complex SQL queries, whereas a Laravel developer extends the Eloquent Model Class and benefits from beautiful and readable database interaction. Zombie Developers often use complicated queries that can lead to bad and infectious code. As a Laravel developer we must keep our queries strong & healthy. We must MODEL some good behavior. Models A model is a PHP class that handles all the interaction between the code and the database. When using Laravel we can extend the Eloquent Model class and all our interaction will automatically be built-in. Take a look at what an example zombie model would look like (this file would be placed inside of the /app folder): name . '
'; 8 echo 'Strength: ' . $zombie->strength . '
'; 9 echo 'Health: ' . $zombie->health . '
'; 10 }); Before we would not be able to run our application because our code would not know where to access the Zombie class, but now that the Model is created we can access it. Note that we are telling our app that when we call Zombie we want to use the zombie class located at App\Zombie. This is referred to as namespaces, something that we will dig further into in a future chapter. We still have a problem, though. We will not be able to access the route from above because we do not have any zombies in our database, so let’s go ahead and create a new zombie with the following route. 1 5 6 7 8 9 10 });
type="text" name="strength" placeholder="Strength">
type="text" name="health" placeholder="Health">
type="submit" value="Create New Zombie"> '; And if we visited that route in our browser (site.com/admin/zombies/create), we would end up with a simple form. When this form gets submitted it will post to the site.com/admin/zombies/create POST route, which should look like the following: 1 all(); // create a new zombie $zombie = new Zombie(); $zombie->name = $post_data['name']; $zombie->strength = $post_data['strength']; $zombie->health = $post_data['health']; $zombie->save(); }); And we submitted the form with the following data: Name: Johnny Bullet Holes Strength: Strong Health: 70 Then we would end up with the following row in our database. How easy is that! We just created our first Zombie. So, if we were to visit the following route (site.com/zombie/1), we would be directed to the following route from above: 1 Route::get('/zombie/{id}', function($id){ 2 3 4 5 $zombie = Zombie::find($id); echo 'Name: ' . $zombie->name . '
'; echo 'Strength: ' . $zombie->strength . '
'; echo 'Health: ' . $zombie->health . '
'; 6 }); And we would see the following output in our browser. Awesome, right? How much easier could it be? Well, it gets a little easier, instead of creating a zombie by adding the name, strength, and health manually we could always do this in one line. Check out the following: 1 2 3 4 5 6 7 8 9 10 11 12 13 all(); // create a new zombie $zombie = Zombie::create($post_data); }); ?> If we tried to submit to the route above, we would probably get an error message saying ‘MassAssignmentException’. This means that we are trying to assign a mass amount of data to our Zombie class, but we have not specified what is ok to add when creating a new Zombie. This is a level of security that Laravel offers. To tell our zombie class that we want to be able to create a zombie and allow name, strength, and health all at once we would add the following in our Zombie class: 1 protected $fillable = ['name', 'strength', 'health']; So, the full class would look like: 1 name . '
'; echo 'Strength: ' . $zombie->strength . '
'; echo 'Health: ' . $zombie->health . '
'; $weapon = Weapon::where('zombie_id', '=', $zombie->id)->first(); echo 'Weapon: ' . $weapon->name . '
'; }); We just introduced another new helper provided by the Eloquent library; this is the where function. Before we just used find which returned the object with an ID. Above we are using Weapon::where('zombie_id', '=', $zombie->id)- >first();. What is happening here is that we want to get the weapon where the zombie_id is equal to our zombie id, and we want to get the first row. You can learn more about all the different ways to retrieve data from our models by checking out the full documentation on Eloquent here: http://laravel.com/docs/eloquent. The above example will get the job done; however, there is an even easier way of doing this. If we specify our relationship between the zombie and the weapon we can minify the amount of code we need to add. We could add our relationship to our Zombie Model, and that would look something like this: 1 hasOne('App\Weapon'); } Above we are saying that a Zombie has one Weapon. We just create a new public function called weapon() and return the weapon. So, with that addition to our Zombie Model we can now refactor our code and display all the information about our Zombie like this: 1 name . '
'; 8 echo 'Strength: ' . $zombie->strength . '
'; 9 echo 'Health: ' . $zombie->health . '
'; 10 echo 'Weapon: ' . $zombie->weapon->name . '
'; 11 }); How great is that! By adding that relationship we just took these two lines of code: 1 $weapon = Weapon::where('zombie_id', '=', $zombie->id)->first(); 2 echo 'Weapon: ' . $weapon->name . '
'; and turned it into this one line: 1 echo 'Weapon: ' . $zombie->weapon->name . '
'; Being more readable and easier to work with, If we now visit (site.com/zombie/1) we should get our output which will look like the following: To see all the information about our zombie with an ID of 2 we could then visit (site.com/zombie/2) One last thing before we move on, what if we had the ID of our weapon and we wanted to see to which zombie it belonged? This can be achieved in the same way. We can add our relationship in our Weapon class, but instead of the hasOne relationship, we will use the belongsTo relationship since a Weapon belongs to a zombie. To add this relationship we will add a zombie method to our Weapons model that will return a Zombie object like so: 1 2 3 4 5 6 7 8 9 10 11 12 belongsTo('App\Zombie'); } } Now, we could add the following route: 1 use App\Weapon as Weapon; 2 3 Route::get('/weapon/{id}', function($id){ 4 $weapon = Weapon::find($id); 5 echo "This " . $weapon->name . " belongs to " . $weapon->zombie->name; 6 }); We can now get to the zombie that owns this weapon by accessing $weapon->zombie. And if we were to visit (site.com/weapon/1) we would get the following output: Using relationships in Laravel makes interacting with your data easy and fun. The relationship between hasOne and belongsTo is referred to as a One-to-One relationship (since each of them has one of the other). If you wish to learn about the other relationships in depth head on over to http://laravel.com/docs/eloquent-relationships. Models and relationships are a big part of what makes Laravel amazing. Instead of creating complex queries and bloated models, we can focus on more the fun stuff and build our application quicker than ever before. Next up we are going to talk about mutators, which allow us to manipulate(mutate) data before it gets entered into or retrieved from the database. Chapter 7 - Mutators A zombie developer does not sanitize data when sending or receiving it from their database, whereas a Laravel developer uses mutators to manipulate data before and after getting data from the database. Mutators are our friends, and they will help us defeat the zombie developer apocalypse by helping us sanitize or manipulate data in our Models. Mutators Mutators allow us to change data before sending it to or retrieving it from the database. When we manipulate data before it gets entered into the database, it is referred to as a Mutator, when we manipulate data after we retrieve it from the database it is referred to as an Accessor. We are going to use a pretty simple example to show you the basics of using mutators. We will use our zombies table as an example from the previous chapters. Let’s say that anytime we get a zombie name from the database we want to make sure the name is capitalized. We could easily do this using an Accessor. In our Zombie Model from our past examples we would want to add the following method: 1 public function getNameAttribute($value){ 2 return ucwords($value); 3 } And now any time we get a zombie name from the database it will be capitalized. You will want to make the name of the function correspond to the name of the database row you want to change. Since our database row was name our function name is getNameAttribute. This can be done just as easy using Mutators, except we will modify the data before it gets put into the database. To add this mutator we would add the following method to our Zombie model: 1 public function setNameAttribute($value){ 2 $this->attributes['name'] = ucwords($value); 3 } The name would also be capitalized before we saved the data to the database. Our full zombie model with our Accessor and Mutator methods would look like the following: 1 attributes['name'] = ucwords($value); } 16 } Most likely you wouldn’t need the Accessor and Mutator to do the same thing, it would be a preference as to which one you wanted to use. From the examples above, if anyone were to enter a zombie name into our database it would be capitalized. Hopefully, you can see the advantage of using mutators; it makes it easy to send and retrieve manipulated or formatted data from your database. Just another awesome functionality to help make our lives as developers easier. Next up we are going to learn about views. Views are the files that typically contain the HTML & CSS. In the previous examples we have just been outputting our data from our routes.php file, but when we want to output data to the screen we will typically use our views. Let’s move on to the next chapter to learn more. Chapter 8 - Views A zombie developer entangles logic and HTML elements in the same page, whereas a Laravel developer separates their views from their logic. Zombies are considered to be messy and not too friendly because they write code all over the place. As a Laravel developer we separate our data output from our data logic. In this chapter, we’re going to talk about using views. Leveraging the powerful features of Laravel will help us gain a clear VIEW of what we want to build (sorry for the cheesy pun). Views Views are essentially the HTML and the layout elements of a page. A view is what our user will see when they visit a page. So, how might we go about creating a new VIEW for a specified route? Glad you asked, as it’s very straightforward. Back in Chapter 2, we created a simple route called ‘graveyard’ that printed out a string, which looked like this: 1
10