Laravel 5.3 For Beginners Book Official Release

Access all tutorials in sprocket icon.

Published September 8, 2016 by Bill Keck.

Laravel 5.3 For Beginners Book Official Release

I’m happy to announce I’ve just released my new book, Laravel 5.3 For Beginners. The book comes in at just over 620 pages, and covers a lot of ground that I did not cover in my previous Laravel books, including using Elixir and Vue.js.

The book starts out with the basics, like the previous books, and some of that will sound familiar if you read those books, but then it progresses into more intermediate code. We utilize Socialite for one-click authentication with Facebook and Github, so now we have it set up to handle multiple social providers. We have an image management trait that helps us utilize the Intervention Image package, which makes creating thumbnails very easy.

Another big difference in this book is the use of Elixir and Vue.js. I didn’t cover those in previous books because I felt they were more intermediate, and actually, Vue.js has only recently been adopted by the community to the extent that is now configured in Laravel out of the box. You will love that.

The whole Elixir implementation is easier to get going now, so we get introduced to Elixir for our asset management. But we don’t do that early in book, we save it for later, after you learn the basics.

Instead we take you step by step in building a sample application that will help you understand how the framework actually works. The early chapters are similar to my last book, but there are significant differences, mostly refinements that reflect both my personal growth as a programmer and also trends within the community. For example, while I still use the form helper for date formatting, I don’t use it for much else and we will explore the reasons for that.

Also, we are no longer using jQuery for our data grids. Instead we moved to a very robust data grid built with Vue.js, the javascript framework that is favored by so many Laravel developers, so much so, it comes setup for you out of the box, after you run npm install.

As always, I did my best to make the book comprehensive and accessible to all. Laravel is just an awesome framework, and if you are just learning, it’s a great place to start.

Thanks again to everyone who has purchased my previous books and followed this blog, I appreciate your support!

Laravel Forge is a Great Tool for Deploying your Application

Access all tutorials in sprocket icon.

October 24, 2015 from author Bill Keck.

Laravel Forge

One of the truly amazing things about the Laravel Framework is the amount of supporting products that are out there in addition to the wonderful free Laravel php framework. I had some interesting insight and discovery with Laravel Forge that I would like to share.

So, I developed my first production app with Laravel, KeyComicBooks.com, which is a fairly simple tool for finding “key” comic books, those worth investing in. Yes, people invest in comic books, but let’s not get into that, you can check out the site if you want to know more about that. It’s actually a fun little site.

Now to deploy it, I had some choices available to me that a lot of people don’t have. I went to our company’s network specialist, the one in charge of provisioning servers, and asked him if he could allocate the necessary resources and show me how to deploy my site. He told me he could do it, but that it would have to wait behind some other priorities. Another programmer at work chimed in and suggested I try Digital Ocean in combination with Forge.

I said, “You want me to do it myself?”

It’s one of those moments when you realize you are about to jump into the deep end, without really knowing how to swim. I think that’s an appropriate metaphor considering the name of the hosting company, Digital Ocean.

So just to be clear, Digital Ocean is a cloud hosting platform and Forge is Laravel’s deployment tool. I didn’t have any prior hands-on experience working with production environments, so this just seemed like it was going to be a grind. On the other hand, I could see the wisdom in jumping in full force, there really is no better way to learn. So that time had come.

I created my Digital Ocean account within about 2 minutes, there wasn’t much to it. I went for the $20 per month plan, which was sufficient for my needs, probably more than sufficient, but I always like to leave room in the resources. So getting that setup was a snap, but then the idea of provisioning everything I needed, PHP, MySql, Composer, Apache (in this case ngnix), node and whatever else just seemed way over my head.

So I opted to try Laravel Forge, which builds and helps you manage your server. Just a quick note, I’m going more in the review direction with this post as opposed to a step by step tutorial. I’m not authoritative enough at this point to give you that. But I can describe the process and tell you how it went for me, and I have to say up front, it was fairly smooth and I love Forge. It is well worth the $10 per month in saved time.

Once you signup for Forge, you link it to your Digital Ocean account, which is fairly simple. It’s a few fields in a form with placeholders that make it intuitive. Then you push a button and it configures your server. This is just awesome.

Next you have to link it to your repository, which again is very simple, but to get it to work, you do have to provide a public key for access from your terminal. I had no idea how to do this, but a little Googling got me on the right path. I was able to generate a public key from my mac and provide that to Forge.

In reality, as a complete newbie, this took about 20 minutes, the most time being spent away from Forge and working on the public key generation, and making the typical mistakes, like copying the private key instead of the public one. But once I cleared that hurdle, I was able to deploy my code to the server.

Did the site function out of the box? No. I had to run the migrations. This means you have to ssh into your server and get into the correct directory and run php artisan migrate. So it took me a few minutes to figure out how to do that the first time.

Then that failed because I didn’t have my server environment file set, so no DB connection. Your .env file does not get uploaded into your repository, so the application has no knowledge of the DB. Luckily, the .env file on the server is really easy to edit via Forge, and it only took a minute to update the DB info.

So then I tried my site and of course uncovered a few bugs I didn’t anticipate. I had an error in my navigation bar that was testing for the presence of a profile, but of course while I was coding I had a profile, but now, with a fresh install, I did not, so this was an untested and overlooked problem. It was a simple fix, and again, pulling in the latest code via Forge is a one click prospect. It’s an awesome flow.

But I still had another problem. I ran into the dreaded token mismatch error. This happens when inside the session.php file, which is in the config directory, the domain is not set to the current url. It took me a while to track that down. I felt really dumb because I had run into this before and forgot about it. So I was covering ground I should have already been aware of. This is one reason why I document so much, I just can’t remember everything, and chasing down bugs like that can consume a lot of time.

I also ran into problems where I had to clear my cache for my routes. So once I got all that done, I had a working site. But there was just one more problem. I did not have access to the backend, and since I could only sign up as a regular user, there was no way for me to create an admin user. One way to handle that might be to create a migration that creates the user with admin status.

But I figured I needed to understand how to interact via Mysql directly on the server anyway, so I updated the user record directly from my terminal. So I had to learn how to access MySql from the command line as opposed to using PhpMyAdmin, which is how I typically work with it. None of that has anything to do with Forge. I’m only mentioning these things because you need to have realistic expectations when deploying. You will probably have to do some refining with your app as well.

After getting my install operating correctly, I started reviewing the site and found things that weren’t right. So now I was changing code, pushing it to the repository, then deploying via Forge. Well Forge had one more feature that made this even easier. It can listen for changes to your repository and automatically push them for you. So I switched that on and it works beautifully.

The automatic update did fail for a period, and I imagine behind the scenes that either BitBucket was having problems, which would not surprise me because that has happened before or Forge’s node server quit or something. Anyway, the problem was temporary and I love how it pulls the code automatically. I just push from my IDE, which is PHP Storm, and in less than a minute the code is both in the repository and live on the server. Very cool.

From my personal experience with Forge, I can say it has been extremely positive. I would be hopelessly lost without it, and at a minimum, it would take a lot of work to learn how to provision manually. There’s wisdom in learning how to do it manually, but my focus is not on environments, and I just don’t have the time now to commit to it. For beginner to intermediate programmers, Forge is just a great tool to work with. Eventually I’ll get some feedback from advanced environment guys to see what they think of it as well.

There’s an indicator button in Forge that shows you the status of deployment. Sometimes deployment can take a few minutes, so it’s really cool to be able to see the progress. I love watching it kick over and show me that my changes are live. It’s a good feeling.

In conclusion, I’m giving Laravel Forge the highest possible recommendation. I don’t feel like I’m drowning any more. I’m actually having fun deploying the application. It doesn’t get any better than that.

Simple Dropdown list from Eloquent List Method Laravel 5.1

Access all tutorials in sprocket icon.

October 4, 2015 from author Bill Keck.

Laravel makes creating a dynamic dropdown list incredibly simple. Let’s say for example, you have a Category model, which holds the categories you want to use in a dropdown list. You can just use the lists method pull out the values you want for the dropdown list:



$categories = Category::lists('category_name', 'id');

This assumes you have id and category_name columns in your categories table. Obviously if you are just calling it ‘name’, then use that.

Then you just need to pass $categories to your view:



return view('yourview.create', compact('categories'));

That returns an array with the values you need, which you can just pop into your dropdown list in your view. I’m using the Collective Form Helper package for my select:



{!! Form::select('category_id', $categories) !!}

And that’s it, you get your dropdown list. Little helpers like this make Laravel a pleasure to work with.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.

Eventing in Laravel 5.1

Access all tutorials in sprocket icon.

September 30, 2015 from author Bill Keck.

Eventing in Laravel 5.1.

Background.

One of the things that can be intimidating when you are a beginner is the idea of eventing. What is it? When to use it?

Probably the easiest way to get it is through a simple example. Think of an email message that gets sent out upon registration of a new user. In the old procedural way of doing it, you would just hardcode some kind of send command directly in the controller.

That does work, however if your application grows, you might have all kinds of messages that need to go out to users, things like support request responses, upgrade messages, and of course the previously mentioned signup responder.

When you put it in that context, it makes a lot of sense to have a clean and extensible way to handle these situations. Events are perfect for this. Laravel events are not limited to email, but this is an excellent way to look at how they work.

Mailhelper.

In my project, I decided to do a fairly robust mail helper class that handles many types of email responses. I haven’t built the system response for registration, so I’m using a class I built to handle support messages. I think if I try to go through that whole process, it would make the tutorial too long, so I’m not going to go through that entire class. Instead, I’ll just show you how I’m calling it:



$contactMailhelper = new ContactMailHelper('supportMessage', $request);

So what that does is it hands in the type of message we want, a support message, and also an instance of the request, which tells it which pre-formatted response we want to send, based on form input. I also did a token replace for username. It’s a fairly involved class, so don’t worry if it doesn’t make sense in a glance. All you need to know is that when it returns, the $contactMailerhelper holds the sendto email address, the subject, the body, and view that’s needed for the message.

If you don’t know how to send email from Laravel, this tutorial will help you with that too. After getting our instance of $contactMailhelper, we are then going to fire our event:



$contactMailhelper = new ContactMailHelper('supportMessage', $request);

event(new RespondedToSupportRequest($contactMailhelper));

Bind the Event to a Listener.

Ok, I’m getting ahead here by showing how it’s called, I’m going to come back to this because we have not yet created our event to handle it. So how do we that? Fortunately, Laravel makes this incredibly easy.

In your Providers folder, you will see a file named EventServiceProvider.php. Inside of that, we will put the following in the $listen array:



protected $listen = [
        'App\Events\RespondedToSupportRequest' => [
            'App\Listeners\MailUserSupportResponse',
        ],
    ];

This binds the event RespondedToSupportRequest to the listener MailUserSupportResponse. Neither of those two classes exist yet either.

Generate the event classes.

We can quickly get both of those classes up and running by using the following artisan command on the command line:



php artisan event:generate

So that command looks for any bindings that don’t currently have classes and creates them for you. If you run that coommand, you now have RespondedToSupportRequest.php in the events folder. You will also have MailUserSupportResponse.php in your listeners folder. Both files are stubbed out and namespaced and in the correct folders. This is just awesome workflow.

We’re not really building a working example, but you should get enough out of this tutorial to be able to setup your own events. So don’t worry if you would rather have a UserSignedUp event with an EmailWelcomeNewUser, just make the changes to the EventServiceProvider $listen array and generate your own events.

I’m going to continue on, because there are few more things that you should know that are really helpful.

Let’s tackle the listener first. All we have to do is modify the handle method:



public function handle(RespondedToSupportRequest $event)
{
        $data = ['body'         => $event->contactMailHelper->emailBody,
                 'emailAddress' => $event->contactMailHelper->emailAddress,
                 'emailSubject' => $event->contactMailHelper->emailSubject,
                 'emailView'    => $event->contactMailHelper->emailView,
        ];

        Mail::queue($data['emailView'],$data , function($message) use($data)
        {
            $message->to($data['emailAddress'])->subject($data['emailSubject']);
        });
}

In the signature of the handle method, we hand in an instance of the event. Then I’ve set up an array for the $data that we need to send an email. In my case, I’m receiving the configuration through the contactMailHelper object that I’m handing in.

If you want to simplify and hardcode in values for a signup email, for example, just replace that code with your own values. You can see that $data is just an array and we are simply using the array keys to hand in the appropriate values at the right places.

I’m also going to show you how to pass along an object, so you will be able to hand in the user instance if you want and you can use something like $event->user->email if you wish. Hopefully that will be clear.

Sending the mail.

The part that actually sends the mail is the following:



Mail::queue($data['emailView'],$data , function($message) use($data)
        {
            $message->to($data['emailAddress'])->subject($data['emailSubject']);
        });

I should mention that Laravel is going to look for view in the emails folder that is in the view folder. The second parameter is $data, so we have So your $data[’emailView’] key should hold that value. Inside the view itself, the array key is a variable you can call:



{{ $body }}

That will display whatever is in the email if you have set that in your $data array. You can reference the Laravel Docs on this as well.

Also, if you want to use Mail, you need to include the use statement:



use Illuminate\Support\Facades\Mail;

Also notice, I’m using the queue method as opposed to the send method. What this does is allow you to push the message to the queue, so you don’t have to stop the user experience to wait for it to process. Instead it gets pushed onto the queue, where it goes out asynchronously from the browser.

The Event.

Let’s go to the RespondedToSupportRequest.php and modify the constructor:



public function __construct($contactMailhelper)
    {
        $this->contactMailHelper = $contactMailhelper;
    }

We also need to set a property:



public $contactMailHelper;

So in my implementation, I’m handing in my instance of $contactMailHelper, which sets all the email properties I’m going to need. If you are doing a simple autoresponder on registration, you might just want to pass along the user id, so you can get the rest of what you need in the handle method of the listener. Like I said, this is not a working example for you, just trying to help you understand how it works.

At any rate, the constructor sets the property, which will be passed along to the listener when the event fires.

So, putting it all together, we call the event in your controller like so:



event(new RespondedToSupportRequest($contactMailhelper));

Don’t forget the use statement:



use App\Events\RespondedToSupportRequest;

That’s just one line you can pop into your controller(don’t forget the use statement), so you don’t end up with mail code in your controller that doesn’t really belong there.

So the $contactMailerhelper object is passed into the event and we know that is set through the constructor of the event for us to use in the listener. The handle method of the listener does the bulk of the work:



public function handle(RespondedToSupportRequest $event)
{
        $data = ['body'         => $event->contactMailHelper->emailBody,
                 'emailAddress' => $event->contactMailHelper->emailAddress,
                 'emailSubject' => $event->contactMailHelper->emailSubject,
                 'emailView'    => $event->contactMailHelper->emailView,
        ];

        Mail::queue($data['emailView'],$data , function($message) use($data)
        {
            $message->to($data['emailAddress'])->subject($data['emailSubject']);
        });
}

This tutorial might seem complicated if you are reading along, but in reality this is very simple. Here are the 4 simple steps to implementation:

1. Bind your event to listener in the EventServiceProvider file.
2. Use the artisan command to generate the necessary classes, php artisan event:generate
3. Modify the constructor of your event class if you need to pass in an $id variable or other object and set the property.
4. Code your handler in your listener class to do act on the event, in our example, it’s sending an email.

Tip: Remember your use statements.

Once you get this, you can see how wonderful and easy Laravel eventing really is. It’s a beautiful part of the laravel architecture, with simple syntax and many advanced features that you can read up on in the docs.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.

Top Ten Reasons To Choose Laravel 5.* For PHP Framework — An Overview

Access all tutorials in sprocket icon.

September 25, 2015 from author Bill Keck.

With so many choices out there about which PHP framework to choose, it can be especially confusing for beginners or those who have never worked with PHP frameworks to figure out which framework merits their time. And right along with that thought comes the question of which was is easiest to learn?

The last question supposes that there is anything easy about learning programming, which, sorry to say, is typically not the case. That said, I can tell you from personal experience that Laravel 5.1 is easier for me to pick up than other frameworks I’ve worked with.

Now that could be because I’m further along on my programming journey than I was when I worked with other frameworks or even no framework. No doubt that plays a role in the ability to pick things up quickly.

That said, I do think there are at least 10 big reasons why Laravel shines as a framework. I’ll list the reasons first, then go over each one:

Top Ten Reasons To Use Laravel:

  1. Excellent Documentation.
  2. Laracasts
  3. Intuitive Syntax
  4. Practical Application Structure
  5. Artisan Code Generation
  6. Out-of-the-box User Model
  7. Blade Templating Engine
  8. Dependency Injection Made Simple
  9. Supporting Products and Packages
  10. Innovative Founder

1. Excellent Documentation

Taylor Otwell, the founder and main developer of Laravel has written the documentation of the framework himself. One of the interesting things about Taylor, which we will see play out in some of the other reasons I’m listing, is that he has an uncanny command of syntax, both in the English language and in programming.

He seems to have an intuitive knack for making things simpler and more digestible, organized in a way that the average programmer can easily consume. His documentation and attention to detail reflect this.

Before I start working with a framework, I read the docs from front to back, before I write a single line a code. That is, I read them if they are readable or understandable, which often they are not. In those cases, I just usually get stuck and give up.

Anyway, the value of great documentation can’t be understated. Here’s a trivial example. I decided to add a checkbox to my registration form to have users accept terms of service. Sounds like a common scenario, does it not?

Now imagine my surprise when I found out that Safari does not support the HTML 5 required tag. No problem, I just need to handle it through Laravel’s validation. So let’s see, the check box will be null or empty string if not checked, err, is that right? Hmm. I wonder what kind of validation Laravel offers to account for this. It would have to be looking for a boolean, right? But then do I have to convert it to a 0 to get it work?

Well, fortunately, the docs on validation are crystal clear and include a section listing all the available out-of-the-box validators. The very first one is the accepted validator. The docs describe it as:



accepted

The field under validation must be yes, on, 1, or true. 
This is useful for validating "Terms of Service" acceptance.

It just can’t get any easier or more clear than that. Notice how he anticipated the use for the validator. Now you might say, wow, that’s just too simple a reason to love a framework, but you have to keep in mind this is a consistent experience across all the docs. I might have to refer to the docs to do a left join, for example, because I just can’t remember everything off the top of my head. Luckily, the docs are just as simple and crystal clear on that too.

2. Laracasts

Laravel is supported by Laracasts, which features a mix of free and paid videos that show you how to use Laravel. The videos are all done by Jeffery Way, who is an expert and well-versed instructor. He seems to have his finger on the pulse of the essentials and offers clear and concise programming instruction. The production quality is high, and the lessons are well-thought out and meaningful.

Laracasts extends out beyond Laravel in terms of content, and this is a huge value add for the site. Laracasts goes into diverse subjects like mastering your IDE, introducing VUE.js, which is a newer javascript framework, to many other great topics, including a series on fundamentals like regular expressions and design patterns.

I can’t really imagine trying to learn PHP and Laravel without subscribing to Laracasts. When a new feature like login throttling comes out, which came out relatively recently, Laracasts always follows with a tutorial.

In many ways, I think Laracasts is a huge competitive advantage for Laravel, because even though it costs money, it supports the framework on level that I have not seen in any other php framework.

My only wish for Laracasts is that they would do more videos. Some episodes on my wishlist: Dynamic and complex forms, Creating a Cart, Query Writing 101, Advanced Query Writing, Writing Queries Like A Rocket Scientist, How To Get Mysql To Dance And Sing… Ah, you get the idea.

Anyway, Laracasts is addicting. It’s kind of like watching your favorite show, you just want more episodes. In this case, watching more episodes means acquiring more skills, which theoretically gives you more earnings potential, so this is one of those pleasurable experiences in life that actually can get you paid.

3. Intuitive Syntax

Robert C. Martin wrote a universally acclaimed book named Clean Code. In the book, Martin shows us how to write code that is descriptive and focused to the task, leading to clearer and more maintainable code.

Taylor Otwell has adopted his principles with Laravel and it just seems to reflect in every nuance of the framework. For example, there is a trait that the AuthController uses named RegistersUsers. Anyone want to guess what that trait does? Well it has 2 methods. One shows the registration form and the other processes the registration.

There are just so many examples of perfect syntax, I can’t even really begin to relate this, but here’s another for example:




$roles = Role::paginate(5);


In this case, we are asking the Role model for all roles, with pagination set to 5 results per page. That’s how simple basic pagination is in Laravel. There’s one additional tag needed in the view, and that’s it. Super simple and super easy to understand.

When I moved into Laravel, I kept thinking, it can’t be this simple…

Ok, one last example:



$role = Role::findOrFail($id);

Here we are using findOrFail to return a single model instance. If it doesn’t get a result, it throws a ModelNotFoundException, which you can then handle with a pretty view page. See my tutorial on exception handling for that. Again, findOrFail is awesome in it’s simplicity and clarity.

Taylor’s feel for syntax, both in English and in PHP, makes Laravel the most accessible PHP framework that I have ever worked with or even attempted to work with.

4. Practical Application Structure

This section was a little difficult to create a title for. The application structure is actually more complex in some ways, but ironically, this makes it easier to work with. So I just think it’s a practical approach.

Years ago, Taylor Otwell described the shortfall of the concept of the model in the mvc pattern in his book, which, incidentally, is not really a book for beginners. When I read it years ago, I was clueless. I reread it not too long ago, not hard because it’s 69 pages in length, and it reads like prediction of what he planned for Laravel 5.

In Laravel 5, he deconstructs the model into more discrete pieces. We get many more folders, which, when I first saw them, made my head explode. I thought it was way too complex, way too much to take in. How dare he make my model folder disappear…

But then as I started using it, I found that while I sometimes had to hunt for the folder, I was able to think in terms of the Laravel application structure much more easily than I could with other frameworks. The organizational sense to it is intuitive, once you get used to it.

For example, it has a folder for Requests, which is in the HTTP folder along with a Controllers folder, routes, a Middleware folder and more. You can’t really just grasp it in one quick glance.

On the other hand, the Requests folder provides the perfect setting for handling validation requests, and you’ll find after using it that it’s very intuitive to think of if that way.

The Middleware folder contains classes for processing the request that act like discrete filters, so for example, the Authenticate class will require the user to be logged in. You can call it on the constructor of the Controller like so:



public function __construct()
{

     $this->middleware('auth');

}

                

What that does is call the auth middleware, which will require the user be logged in. The constructor calls it, then it returns true or false, true if the user is logged in. If not they are denied access. It’s just so simple.

So this is an innovative approach, and at first it seemed a little harder to grasp, but once you get it, you see just how cool it is, and it’s easy to work with. It gives you an incredible amount of flexibility.

One of the finest points of the Laravel Application Structure is the app.php file that sits in the Config folder. This is where you add service providers to the application, and you will do this when you add packages or create your own service providers.

Service providers are autoloaded by the framework so you have access to the classes. In the aliases array, you provide references to the classes so you can access them via a facade, which is just a map to a particular class. This can sound complicated, but in practice, it is very easy to work with.

Like I said, I can’t call the application structure simple, because it has a lot of different pieces to it that I haven’t seen elsewhere, but it is easy to work with, and it ends up being more intuitive because of that. To me, that means it is a very practical structure.

5. Artisan Code Generation

Laravel ships with a great command line tool named Artisan. Need to make a controller? Try this on your command line:



php artisan make:controller   SampleController

Just hit enter and you’ve got a controller stubbed out for you, and located in the correct folder. If you want to make a request class to hold some validation for a form input, perhaps on a profile model, try:



php artisan make:request   ProfileRequest

And that will appear in your Requests folder for you, stubbed out, namespaced and ready to code.

Migrations are a snap too:



php artisan make:migration   add_is_admin_to_users_table

That will create a migration in the migrations folder.

And on that note, tying back to the importance of well-written documentation, the docs cover all the migration commands, so you are never lost.

I had a lot of resistance to working with migrations. I thought they were a cheeseball approach to data-modeling. But when I started working with Laravel, I decided to follow along with the work flow as closely as possible. Once I got used to creating migrations, I realized they were pretty simple to work with, and you get added benefits. When you collaborate on projects, remote team members can run the migrations and have the same exact DB structure, which is great way to manage that. It really is so easy to work with, you will love it.

6. Out-of-the-box User Model

Something I was glad to see out-of-the-box in Laravel 5 is the user model. You get the controllers and migrations that you need to setup the users table and a fully working user registration and login system, with forgot password functionality.

Laravel does require you to write the routes and views on your own, and I provide a handy tutorial for that purpose.

Having a ready-made user model let’s you get your projects up and running quickly and it’s much appreciated. It’s also nice to have the forgot password functionality there because that involves setting tokens that expire, which can be fairly complicated and time-consuming to setup. It’s cool to have this done before you even start.

7. Blade Templating Engine

The Blade templating engine is so intuitive and makes working with the typical PHP/HTML spaghetti so much better, that’s it one of the best features of the framework. If you ever have had to chop up an if statement with HTML inside of it, you know exactly what I mean. But with blade, it’s almost effortless:



@if(Auth::check())

//show the html you want for when the user is logged in.

@else

// show other html when the user is not logged in.

@endif

I won’t get into an entire tutorial here, but Blade is just a pleasure to work with. As we all know, working with your javascript files and CDN calls can be tricky. It’s really easy with Blade, lots of flexibility on how you deal with that.

If someone could just invent a javascript framework that is as easy to work with as Laravel, and plays nice with Laravel, that would be awesome. If it already exists, and you know about it, please share by leaving a comment.

Blade compiles everything, so you don’t incur any overhead for using the template engine and that is just wonderful. Again the syntax is just perfection. Work with it and you’ll see what I mean.

8. Dependency Injection Made Simple

If you been coding in PHP in the last few years, you’ve no doubt heard a lot of buzz about dependency injection. Although it sounds complicated, it’s actually pretty simple in the context of Laravel.

Dependency injection allows you to code to a contract instead of a concrete class, the benefit being that you can easily swap out implementations with minimal impact on the code. It is centered on this idea of loose-coupling of classes which makes your code more extensible and easier to maintain.

You can look at the app.php file in config as an example of loose-coupling. You can easily swap out service providers, which are the building blocks of the application.

Ok, so when I first heard about this, it all seemed so gratuitous to me. I didn’t quite understand the benefits of contracts, which are interfaces, and the concept of loose coupling. I felt like it made no sense for medium to smaller size applications by adding unnecessary complication. It just seemed like overkill. I was really wrong about that.

Laravel adheres to these principles in a very intuitive way, and rather than create convolution, it actually makes things simpler. The implementation is somehow simpler than explaining the concept in detail. You can check out my tutorial on creating a service provider, if you want to see an implementation that will help you understand it better.

Laravel also supports method injection, which is when you type hint a class in the method signature like so:



public function show(Request $request, $id)
{


    $input = $request->all();

}

So in the above, Request type hints an instance of the Request class, which means we have now have an instantiated instance named $request, and this is typically what you are going to see for capturing form data. Also in the above, you can see we are grabbing all the form input and assigning it to a variable named $input. Look at how concise and intuitive that is.

This is a top ten list, not a tutorial, so I won’t take it further, but I think you get the idea of how Laravel is doing innovative things. When you work with it, you’ll find it’s really not that complicated after all.

9. Supporting Products and Packages

Laravel is well-supported by many packages that will help you move your project along quickly. I wrote a top ten list of Laravel packages, so I won’t repeat that here.

In addition to all that, Taylor Otwell has brought out a number of products in the Laravel family that combine into a very powerful suite of products and services. These include Lumen, Elixer, Forge, Homestead, and Envoyer. These are products that will help you in numerous ways, everything from local environment (Homestead) to deployment (Forge, Envoyer). And I should mention again that Laracasts as an educational support component is just phenomenal. Our company purchased a company license, so all of our developers can have access to it. It’s well worth the money.

In some ways, Laravel is more like a commercial product than an open source library and I say that as a strength, not a weakness. It has the polish and the support to make it easy to work with. Maybe I should say easier. I don’t want to give the impression that everything is easy, because as we all know, programming is not easy. That said, Laravel takes you as close to the promised land of coder happiness as I have ever seen with PHP.

10. Innovative Founder

I’ve never met Taylor Otwell. But I have watched Laravel since 2012 and I have seen it go from the wobbly new kid on the block to the dominant PHP framework. It’s not an accident. Taylor is the driving force behind the framework and continually pushes out innovative products.

A couple of examples are Lumen, an uber-fast micro-framework and Laravel Spark, a SAAS template built in Laravel now in alpha. And the features in Laravel continue to evolve as well.

On that note, I learned a lesson recently. I decided to simplify the AuthController and bypass the auth traits, just to make it easier for me to work on things like login and registration. Looking back, it wasn’t really easier, but that is what I thought at the time. The right word is I made it more familiar, not easier. And of course I shared this via tutorial.

Then 2 months after writing the tutorial, I noticed that people were saying the code was broken. How could that be? Well, it turns out Taylor released an update, and as part of that update, he changed some of the underlying code to allow for a new throttles logins feature, which built in a defense against bots attacking the login. That’s a great feature.

Because I had moved away from the framework code, I couldn’t take advantage of it. And my code was broken. So I decided to rewrite the tutorial.

This time I stuck to the framework code. If I want to change something, I’ll pull the method up to the AuthController and overwrite it, that way I don’t mess with the framework code. This will make it easier for me to adapt to changes, and of course take advantage of new features as they are released.

This way I can ride the lightning of Taylor’s innovation. It’s a great thing and it is having a huge and positive influence on the PHP community. Coding in PHP is becoming easier thanks to Taylor Otwell, it’s that simple.

In conclusion, my personal experience with Laravel is that it has simultaneously made me a better programmer and made it simpler to write code. If I sound like an enthusiastic supporter of Laravel, I am. It’s made my coding life more productive and enjoyable and that’s a wonderful thing to get from a free PHP framework.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks.

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.

Charts in Laravel 5.1 with Morris.js

Access all tutorials in sprocket icon.

August 22, 2015 from author Bill Keck.

Charts in Laravel 5.1

Charts are great way to spice up UI and the Morris.js Chart is fairly easy to implement, so that is what we are going to use for our lesson.

This tutorial builds on the following tutorials:

You don’t need to use a Morris.js chart with our Widget model, but it does make it easy to follow along for the data formatting part.

Part 1. The Chart

We’re going to build a chart for our index page in our Widget model, which is just a generic model that I’m using in my tutorials. We have a Widget model, a WidgetController and corresponding views, including an index view and a search results view named resultsindex.

This means we can have a chart for all records, which are displayed on the index view and also a chart for specific search results, which are displayed on the resultsindex view.

We’re going to start with the views and work our way backwards. Let’s look at our views/widget/index view:



@extends('layouts.master')

@section('title')

    <title>The Widget Page </title>

   @endsection

@section('css')

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">

@endsection

@section('content')

   {!! Breadcrumb::withLinks(['Home' => '/', 'Widgets' => '/widget']) !!}

   @include('widget.noresults')

    <br>

   @include('widget.searchform')

   @if(isset($results))

       @include('widget.searchresults')

       @else

        <h1>Widget Stats </h1>

        // insert a div id with a value of chart

        <hr>

       @include('widget.allrecords')

       @endif

@endsection

@section('scripts')

    //cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js
    //cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js

    

       function ConfirmDelete()
       {
           var x = confirm("Are you sure you want to delete?");
           if (x)
               return true;
           else
               return false;
       }

    
    
       var data =  ;

       Morris.Line({
           element: 'chart',
           data: data,
           xkey: 'year',
           ykeys: ['count'],
           labels: ['widgets created']
       });
    

@endsection

Note: Once again wordpress is chomping my code. So you have to insert a div id with a value of chart where I have indicated // insert a div id with a value of chart.

It’s also missing the opening and closing script tags within the @section(‘scripts’), so you will have to add those as well.

I have created a gist with the full code for reference and convenience to copy.

Also note that if you are not using the Bootstrapper package, then chop out:

{!! Breadcrumb::withLinks([‘Home’ => ‘/’, ‘Widgets’ => ‘/widget’]) !!}

Ok, let’s look at the parts that are specific to the Morris Chart implementation. We’ll start with pulling in the css through CDN:



@section('css')

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">

@endsection

Since we have an @yield(‘css’) on our Master page, the contents inside the @section(‘css’) tags will be injected, so we have our css.

Next we have within our @section(‘content’), our h1 tag and chart div:



 <h1>Widget Stats </h1>

        // insert a div id with a value of chart

        <hr>

Note: Once again wordpress is chomping my code. So you have to insert a div id with a value of chart where I have indicated // insert a div id with a value of chart.

Here again is the gist with the full code for reference and convenience to copy.

I use a simple <hr> to separate from the rest of the content, so nothing fancy about that. Our chart div is where the actual chart will go. You can see I’m specifying height.

Next we have our @section(‘scripts’), which is where we will bring in the morris.js files via CDN:



@section('scripts')

    //cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js
    //cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js

Then we have a script for our alert on the delete button, which has nothing to do with chart so I’m going to skip it. That brings us to the script for the chart:



    
       var data =  ;

       Morris.Line({
           element: 'chart',
           data: data,
           xkey: 'year',
           ykeys: ['count'],
           labels: ['widgets created']
       });
    

@endsection

Don’t forget to add the opening and closing script tags.

You can see we are setting var data the result of json encoded $chartData. Before we encode it, it looks like this:



array:4 [▼
  0 => array:2 [▼
    "year" => "2012"
    "count" => "3"
  ]
  1 => array:2 [▼
    "year" => "2013"
    "count" => "1"
  ]
  2 => array:2 [▼
    "year" => "2014"
    "count" => "3"
  ]
  3 => array:2 [▼
    "year" => "2015"
    "count" => "45"
  ]
]

This is what it looks like after json encoding:



[{"year":"2012","count":"3"},
{"year":"2013","count":"1"},
{"year":"2014","count":"3"},
{"year":"2015","count":"46"}]

So obviously our $chartData is returning year and the count of widgets created within that year. You make a chart from any data you like, you just need to format it correctly in json format.

Next we have the config:



 Morris.Line({
           element: 'chart',
           data: data,
           xkey: 'year',
           ykeys: ['count'],
           labels: ['widgets created']
       });

Morris.Line will display the results as a line chart, while Morris.Bar will display it as bar chart. We are assigning the results to the chart element, which in our implementation is a div id.

Next we are using the data variable that we created as the source of the data. Then we assign the year key to the xkey and the count to ykeys. We designate the labels to say widgets created.

And that’s pretty much all you need on the morris.js side of the equation, which makes this so easy to work with. For those of you who know how to do the queries on your model to produce the $chartData results, you probably don’t need to continue.

One thing to note however is that the Morris.Line implementation, as opposed the .Bar implementation, requires all data to be of type string. Since I’m not a javascript wizard, I did the conversion before encoding $chartData. You can handle that however you wish.

The implementation resultsindex view is exactly the same as for index, so just repeat the steps from above, if you are following along with the Widget model and views. Since it is the same, you can also extract it out to a partial, but I will leave that up to you to implement.

Part 2. Building a Chart Helper

So the second part of this tutorial deals with extracting the $chartData from the model. This got a little complicated because of the formatting issues, where the year has to be a string, which made it bloat the controller.

Because of that, I extracted it out to a helper class. Basically, I wanted to be able to get the chart data with a single line in the controller:



$chartData = $chart->chartDataFromAllRecords();

To be able to use $chart, which is an instance of our WidgetChart class, I inject the instance into the method like so:



public function index(WidgetChart $chart)
{

One of the really cool features in Laravel 5.1 is that it will instantiate the instance for you, as long as you have included the use statement:



use App\Charthelpers\WidgetChart;

So there is no need to new up an instance of the class, Laravel does it for you.

For reference, I’m going to give you the entire index method from the WidgetController. This is so if you are following along from the earlier tutorials, you can see exactly how I use it:



public function index(WidgetChart $chart)
{

  $widgets = Widget::paginate(10);

   $count =  DB::table('widgets')->count();

  if (session()->has('message')){

      Session::flash('noResults', 'Sorry, we found 0 results');
   }

   $chartData = $chart->chartDataFromAllRecords();


   return view('widget.index', compact('widgets', 'count', 'chartData'));
}

So just 3 variables sent to the view, a paginated instance of Widget, the count of all records, and $chartData.

If you haven’t been following the other tutorials and this doesn’t make sense to you, it’s ok. The important part is how we are using our instance of WidgetChart to send along $chartData.

Ok, since we have not yet created the helper class, let’s do it now. Within your app folder, create a folder named CharHelpers. Inside the ChartHelpers folder, create a php file named ChartHelper.php, with the following contents:



 <?php
namespace App\ChartHelpers;

use App\Widget;
use DB;

class WidgetChart
{

   public function chartDataFromAllRecords()
   {

       $yearCounts = Widget::select(DB::raw('year(created_at) as year'),
           DB::raw('count(widget_name) as `count`'))
           ->groupBy('year')
           ->having('year', '>', '2011')->get();

       $chartData = $this->formatResultOf($yearCounts);

       return $chartData;

   }

   public function chartDataFrom($searchTerm)
   {

           $yearCounts = Widget::select(DB::raw('year(created_at) as year'),
               DB::raw('count(widget_name) as `count`'))
               ->where('widget_name', 'LIKE', '%'. $searchTerm .'%')
               ->groupBy('year')
               ->get();

           $chartData = $this->formatResultOf($yearCounts);

           return $chartData;

   }

   protected function convertToString($results)
   {
       foreach ($results as $key => $val)
       {

           foreach ($val as $k => $v)
           {


               if (is_numeric($v))
               {

                   $results[$key][$k] = (string) $v;

               }

           }
       }

       return $results;
   }

   /**
    * @param $yearCounts
    * @return mixed
    */
   private function formatResultOf($yearCounts)
   {
       $results = $yearCounts->toArray();

       $chartData = $this->convertToString($results);

       return $chartData;
   }


}

You can see our namespace declaration, use statements, and class declaration:



namespace App\ChartHelpers;

use App\Widget;
use DB;

class WidgetChart
{

First we have our chartDataFromAllRecords method:

public function chartDataFromAllRecords()
   {

       $yearCounts = Widget::select(DB::raw('year(created_at) as year'),
           DB::raw('count(widget_name) as `count`'))
           ->groupBy('year')
           ->having('year', '>', '2011')->get();

       $chartData = $this->formatResultOf($yearCounts);

       return $chartData;

   }

We call the select method on the Widget model and then we are using DB::raw, so we can use raw sql to get what we need. In this case, we want the created_at date returned in a year format, labeled as year, and we also want a count of widgets, and we group everything by year. We also set a condition of having year > 2011, which means any widgets before 2011 will not be included. I figured I would throw in an example of that as an extra tip. The results get assigned to $yearCounts.

Next we use our formatResultOf method to format $yearCounts and assign it to $chartData, which we then return. Two things have to happen, first we need the results in an array, second, we need the year to be a string. So inside the formatResultOf method:



private function formatResultOf($yearCounts)
{
   $results = $yearCounts->toArray();

   $chartData = $this->convertToString($results);

   return $chartData;
}

We format the $yearCounts object as an array and assign it to the variable $results. Then we feed $results into our convertToString method:



protected function convertToString($results)
{
   foreach ($results as $key => $val)
   {

       foreach ($val as $k => $v)
       {


           if (is_numeric($v))
           {

               $results[$key][$k] = (string) $v;

           }

       }
   }

   return $results;
}

Don’t you just love nested foreach loops? In this case, $val is an array, so to get to our year, we need to check if $v is_numeric, and if so, cast it to a string, using (string). I always get tripped up on the array syntax, but this is correct:



$results[$key][$k] = (string) $v;

So with each pass, it puts the value into the array as a string. Then we simply return the array as $results.

Getting back to our formatResultsOf method, which uses the convertToString method as follows:



$chartData = $this->convertToString($results);

We now have our $chartData in a format that can be converted to json, so we simply return it:



return $chartData;

So that covers what we need when we want to return all results from the model for the chart, but in our case, we also have a second method for returning the results of a search, which takes in $searchterm as a parameter:



public function chartDataFrom($searchTerm)
{

       $yearCounts = Widget::select(DB::raw('year(created_at) as year'),
           DB::raw('count(widget_name) as `count`'))
           ->where('widget_name', 'LIKE', '%'. $searchTerm .'%')
           ->groupBy('year')
           ->get();

       $chartData = $this->formatResultOf($yearCounts);

       return $chartData;

}

You can see the only difference is that we have the where clause:



->where('widget_name', 'LIKE', '%'. $searchTerm .'%')

If you are following along with the WidgetController, I have made a gist for the search method, so you can see how we have used the chartDataFrom method.

That concludes the WidgetChart class. You can see this ended up being more than what we would want in our controller, and formatting results is not the responsibility of the controller.

We could have gone even further by coding to contract instead of a concrete class. We could have set up a contracts folder within the ChartHelpers folder, and then within that made a ChartHelpersContract.

If you would like to go in that direction, check out my tutorial on how to setup a service provider, and implement a service provider for the ChartHelpersContract.

In my case, I didn’t feel it was necessary for my application, but you should decide what is right for you.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials.

Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work, you can do so by buying one of my 99¢ books, I really appreciate it.

Handling Exceptions and Custom Exceptions in Laravel 5.1

Access all tutorials in sprocket icon.

August 19, 2015 from author Bill Keck.

Handling Exceptions & Custom Exceptions in Laravel 5.1

One of the more intimidating aspects of learning programming for me has been throwing exceptions, when to do it, how to do it, etc. They just seem scary for whatever reason, but last night I watched a great video on Laracasts about them.

While the video was very informative, it didn’t show me exactly how to setup a custom exception in Laravel 5.1, so I thought this would make a great tutorial.

Out of the box, Laravel 5.1 comes with an Exceptions folder that sits in the app folder. Within that is the Handler.php file, which we can modify to handle all exceptions, including any custom exceptions we want to throw. This is Handler.php file you get with the standard install:



<?php

namespace App\Exceptions;

use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
   /**
    * A list of the exception types that should not be reported.
    *
    * @var array
    */
   protected $dontReport = [
       HttpException::class,
   ];

   /**
    * Report or log an exception.
    *
    * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
    *
    * @param  \Exception  $e
    * @return void
    */
   public function report(Exception $e)
   {
       return parent::report($e);
   }

   /**
    * Render an exception into an HTTP response.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Exception  $e
    * @return \Illuminate\Http\Response
    */
   public function render($request, Exception $e)
   {
       return parent::render($request, $e);
   }
}

Probably the most common exception we come across is the ModelNotFoundException, which is going to get thrown if you type an id into the url that doesn’t exist. For example:



yourproject.com/widget/15

If there is no widget record 15, you will get the ModelNotFoundException, which is very helpful to a programmer, but is not what we want the end user to see. So we have to handle this exception when it’s thrown in a way that is digestible to the end user.

To do this, we are going to modify Handler.php to the following:



<?php

namespace App\Exceptions;

use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class Handler extends ExceptionHandler
{
   /**
    * A list of the exception types that should not be reported.
    *
    * @var array
    */
   protected $dontReport = [
       HttpException::class,
   ];

   /**
    * Report or log an exception.
    *
    * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
    *
    * @param  \Exception  $e
    * @return void
    */
   public function report(Exception $e)
   {
       return parent::report($e);
   }

   /**
    * Render an exception into an HTTP response.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  $e
    * @return \Illuminate\Http\Response
    */
   public function render($request, Exception $e)
   {
       switch($e){

           case ($e instanceof ModelNotFoundException):

               return $this->renderException($e);
               break

           default:

               return parent::render($request, $e);

       }
   }

   protected function renderException($e)
   {

      switch ($e){

          case ($e instanceof ModelNotFoundException):
              return response()->view('errors.404', [], 404);
              break;

          default:
              return (new SymfonyDisplayer(config('app.debug')))
                     ->createResponse($e);

      }

   }


}

You can see that we have set up a switch statement in our render method to determine which kind of exception we are throwing:



 switch($e){

           case ($e instanceof ModelNotFoundException):

               return $this->renderException($e);
               break

           default:

               return parent::render($request, $e);

       }

So we either determine it’s a ModelNotFoundExcpeption or not. The reason I’m using a switch statement here is that I want to make it easy to add other exceptions, which we will show an example of shortly.

If it is a ModelNotFoundExcpeption, then we call the renderException method, which has it’s own switch statement:



switch ($e){

          case ($e instanceof ModelNotFoundException):
              return response()->view('errors.404', [], 404);
              break;

          default:
              return (new SymfonyDisplayer(config('app.debug')))
                     ->createResponse($e);

      }

Obviously, with one exception type, this isn’t really necessary, you could just return the view in the render method. But I’m doing it this way to give myself flexibility as I build out my application.

So now we have a way to handle a ModelNotFoundExcpeption, but we don’t have the corresponding view. So let’s create that now.

Laravel 5.1 comes with an errors folder located in resources/views. Inside the errors folder, create a errors.404.blade.php file with the following contents:



@extends('layouts.master')

@section('content')

//use bootstrap alert div with dismissible

Oh Snap! We can't find what you are looking for...

//end alert div

@endsection

Note: for some reason wordpress has decided to chomp my escape tags, so you are not seeing the HTML for the above. Instead, I’m just including comments for the bootstrap alert div. For your convenience, I’ve linked to the alert markup from the getBootstrap site, so you can just grab it from there.

I have also created a gist so you can get the full code there.

Also note I’m assuming you have a master.blade.php file located in a folder named layouts. If you don’t know what a master page is, please check out my tutorial on Creating A Master Page.

Ok, so that is all you need to run something like:



yourproject.com/widget/78

Assuming there is no widget 78, you will get the nicely formatted exception. You can adjust your error message however you wish.

Ok, so how do we add a custom exception? I don’t have a use case for one, so I’m just going to pick something out of the air and call it ReallyFriendlyException. Let’s create a ReallyFriendlyException.php file in our Exceptions folder with the following contents:



<?php

namespace App\Exceptions;

class ReallyFriendlyException extends \Exception
{


}

Note the namespace. You will have to pull in the correct use statement in our Handler.php file, which can be difficult to debug if you have typos. Just a heads up there.

In this case, we are keeping it super simple, and we don’t even need anything in our class.

Next we need to modify our Handler.php file to the following:



<?php

namespace App\Exceptions;

use Exception;
use App\Exceptions\ReallyFriendlyException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class Handler extends ExceptionHandler
{
   /**
    * A list of the exception types that should not be reported.
    *
    * @var array
    */
   protected $dontReport = [
       HttpException::class,
   ];

   /**
    * Report or log an exception.
    *
    * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
    *
    * @param  \Exception  $e
    * @return void
    */
   public function report(Exception $e)
   {
       return parent::report($e);
   }

   /**
    * Render an exception into an HTTP response.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  $e
    * @return \Illuminate\Http\Response
    */
   public function render($request, Exception $e)
   {
       switch($e){

           case ($e instanceof ModelNotFoundException):

               return $this->renderException($e);
               break;

           case ($e instanceof ReallyFriendlyException):

               return $this->renderException($e);
               break;

           default:

               return parent::render($request, $e);

       }
   }

   protected function renderException($e)
   {

      switch ($e){

          case ($e instanceof ModelNotFoundException):
              return response()->view('errors.404', [], 404);
              break;

          case ($e instanceof ReallyFriendlyException):
              return response()->view('errors.friendly');
              break;
          default:
              return (new SymfonyDisplayer(config('app.debug')))
                     ->createResponse($e);

      }

   }


}

So in the above, we added a case statement in both methods. In the render method, we added:



case ($e instanceof ReallyFriendlyException):

               return $this->renderException($e);
               break;

And in the renderException method, we added:



case ($e instanceof ReallyFriendlyException):
              return response()->view('errors.friendly');
              break;

So you can see how easy it will be to add and handle exception types to our application. We don’t have the view errors.friendly yet, so let’s make an friendly.blade.php file in our errors folder with the following contents:



@extends('layouts.master')

@section('content')

//div for bootstrap dismissable alert

 Oh Snap! You threw a Really Friendly Exception...


//end alert div

@endsection

Again note: For some reason wordpress has decided to chomp my escape tags, so you are not seeing the HTML for the above. Instead, I’m just including comments for the bootstrap alert div. For your convenience, I’ve linked to the alert markup from the getBootstrap site, so you can just grab it from there.

I have also created a gist with the full code.

Now to demonstrate, I’m just going to go to one of my controllers and pop it into the create method, since that is a one line method:



public function create()
{
   throw new ReallyFriendlyException;
   //return view('widget.create');
}

And now we can test it:



yourproject.com/widget/create

And you should get your ReallyFriendlyException. It’s really very simple. Now obviously you could do more with it, optimize the code, etc., but this just gives you an idea of how it all stitches together and how easy it is to create your own custom exceptions in Laravel 5.1.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials.

Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.