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.

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.

Creating Views in Laravel 5.1

Access all tutorials in sprocket icon.

August 18, 2015 from author Bill Keck.

Creating Views in Laravel 5.1

Please note that this tutorial builds on previously tutorials, which, if you want to follow along exactly, you should read first:

Also note that your actual workflow may differ from the tutorials, it is not necessary to adopt a workflow that creates a model first for example. I only did it this way to make it easy for me to demonstrate. Different developers have their own approaches, so you will have to determine that for yourself.

So from our Restful Controller Tutorial, we have a WidgetController with 8 methods:

  • index
  • create
  • store
  • show
  • edit
  • update
  • destroy
  • search

I added the 8th method, search, so that is not a standard method that you get when you create a controller using artisan. Of the methods that come out-of-the-box, the following would have corresponding views:

  • index
  • show
  • create
  • edit

The destroy method is more of an action, it doesn’t require a dedicated view, so it is not on the list.

Typically, an index view is used to show a list of results. The show view is often used to show the details of an individual record. The create method typically shows a form for creating a new record, and edit shows a form for updating a specific record.

Now if you are building an application with multiple models, as most applications will have, then you need to create a folder within the views folder with the name of the model you are building views for. In our case, this will be the widget folder, so go ahead and create that now.

If we didn’t have a folder for our views within the views folder, we would only be able to use the filename index once, which is not what we want. Obviously, we are following a pattern, and we want to be able to use this pattern for all models.

You probably know by now that views use the blade template engine. Blade is a fantastic templating engine that provides us with easy to use syntax, allowing us to mix php and html much more easily than we could without it. We will see this in action in a minute.

Another benefit to Blade is that it compiles the files into standard PHP, so you don’t incur server overhead by using it. This is just awesome.

The Blade file names follow this convention:



index.blade.php
show.blade.php

Anyway, you get the idea. Without further ado, create a widget folder in the views folder. Then you need to create an index.blade.php file within that folder. Then change the index.blade.php file to:



@extends('layouts.master')

@section('title')

    <title>The Widget Page </title>

   @endsection

@section('content')

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

   @include('widget.noresults')

    <br>

   @include('widget.searchform')

   @if(isset($results))

       @include('widget.searchresults')

       @else

       @include('widget.allrecords')

       @endif

@endsection

@section('scripts')
    <script>

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

    </script>

@endsection

Let’s just knock this down one line at a time. We start with:



@extends('layouts.master')

The @extends allows us to inject the pieces of our view into a master page. In this case, we are telling it we want to extend layouts.master. The layouts folder is inside the views folder if you have followed the tutorial on creating a Master page. And the actual master page is master.blade.php.

For more information on creating a Master page, please see my tutorial on Master pages.

Next we add an @section tag, which let’s us insert a section into the Master page:



@section('title')

    <title>The Widget Page </title>

   @endsection

So in the Master page, there is an @yield(‘title) tag, and this is where this section is injected. In this case, we want the <title> </title> for this page.

Next we have an opening @section(‘content’) tag. Everything that falls between @section(‘content’) and @endsection(‘content’) will be injected into @yield(‘content’) in the master page.

After the opening @section(‘content’), we have:



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

If you have the Laravel Bootstrapper package installed, this prints a beautiful Bootstrap breadcrumb to the view. If you don’t have it, you can get the installation instructions from my top 10 Laravel packages tutorial. If you don’t want to use it, just chop it out.

Next we have:



  @include('widget.noresults')

    <br>

Here we are including a view partial. This include statement is calling noresults.blade.php inside of the widget folder, which is inside the view folder.

Since that doesn’t exist, let’s create it now. Place the following in noresults.blade.php:



 @if (Session::has('noResults'))

    <div class="alert alert-error" role"alert">{{ Session::get('noResults') }} </div>

   {{  session()->forget('noResults') }}

@endif

Ok, this walks us right into a control structure using Blade. Referencing the WidgetController index method:



public function index()
{

  $widgets = Widget::paginate(10);

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

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

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

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

You can see we are passing noResults via session. The point is that if noResults is present in the session, we show an alert:



  <div class="alert alert-error" role"alert">{{ Session::get('noResults') }} </div>

That is Bootstrap alert with Blade syntax echoing the Session value of ‘noResults.’ Everything between the {{ }} is an echo statement for php. You can see how clean and readable that is.

When you need to echo without escaping html, use {!! !!}. We will see an example of that soon.

The last thing we do in the if statement is unset the session:



{{  session()->forget('noResults') }}

The purpose of the noresults.blade.php view partial is to produce the ‘Sorry, we found 0 results’ message when there are no results from a search query.

Just to keep it clear, let’s look at the partial again:



 @if (Session::has('noResults'))

    <div class="alert alert-error" role"alert">{{ Session::get('noResults') }} </div>

   {{  session()->forget('noResults') }}

@endif

The reason why we extracted this is to keep our code in index.blade.php as clean as possible. It also allows for reuse of code. If we had several models that used a session to return a no results message, we could put the view partial in a folder named partials, then reuse it for multiple views. This cuts down on code duplication and is ultimately much easier to maintain.

Ok, back on index.blade.php, our next line is:



@include('widget.searchform')

So what we have here is a view partial for the search form. Since we don’t have that file yet, let’s go ahead and create searchform.blade.php now:



 <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
    <div class="panel panel-default">
        <div class="panel-heading" role="tab" id="headingOne">
            <h4 class="panel-title">
                <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
                    <span class="glyphicon glyphicon-search" aria-hidden="true"> </span> Search
                </a>
            </h4>
        </div>
        <div id="collapseOne" class="panel-collapse collapse " role="tabpanel" aria-labelledby="headingOne">
            <div class="panel-body">
                <h1> Search For a Widget </h1>

                <hr/>

               @include('errors.errors')

                <form class="form-horizontal" role="form" method="POST" action="/widget/search">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">

                    <div class="form-group">
                        <label class="col-md-4 control-label">Enter Widget Name </label>
                        <div class="col-md-6">
                      <input type="text" class="form-control" name="widget_name" value="" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-md-6 col-md-offset-4">
                           <button type="submit" class="btn btn-primary">
                               Search
                            </button>


                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>


 </div>

 <br>

Most of this is straight Bootstrap. I added a glyphicon to the label on the panel. Keep in mind when you see all this put together, that frontend development is not a core strength for me. I’ve tried to keep it as simple as possible.

Please note that in order for this to work, your master page will have to reference Bootstrap’s dependencies. You can check out my Master Page Tutorial for details on that.

So we added the form within the panel-body tag. You can see we are calling a partial errors.errors. If you don’t have that, let’s make the errors folder within the views directory now. Then within that, place the errors.blade.php with the following contents:



@if (count($errors) > 0)
    <div class="alert alert-danger">
        <strong>Whoops! </strong> There were some problems with your input. <br> <br>
        <ul>
           @foreach ($errors->all() as $error)
                <li>{{ $error }} </li>
           @endforeach
        </ul>
    </div>
@endif

So here we have another if statement. The $errors object is always available to the view. So in this case, we are checking if the count is greater than 0, and if so, we display the message and iterate through the errors, using blade’s foreach syntax.

Interspersed php and html can be a real mess. Blade’s intuitive syntax just makes it incredibly easy to read and a pleasure to work with.

Ok, so that’s the errors.errors view partial, which we can use whenever we have a form that can possibly return errors, such as invalid input or empty fields that need to be required.

You can see that we are nesting partials, and just how effective and focused this code is. Separating the code like this makes it way easier to work on and maintain in the long run.

Getting back to the searchform.blade.php partial, we open the form:



  <form class="form-horizontal" role="form" method="POST" action="/widget/search">

In the action, we are listing the url that matches a route that we created for widget/search. Next:



   <input type="hidden" name="_token" value="{{ csrf_token() }}">

You can see that we included csrf_token via the blade syntax:



{{ csrf_token() }}

We only have one input for our form, I kept it simple. Most forms will have more than one field.



 <div class="form-group">
          <label class="col-md-4 control-label">Enter Widget Name </label>
          <div class="col-md-6">
          <input type="text" class="form-control" name="widget_name" value="" required>
          </div>
  </div>

This is Bootstrap form syntax. You can see I added the name of the attribute, widget_name and placed required at the end of the tag. This will force it to have a value before being submitted.

The last thing of note is the submit button:



 <div class="form-group">
        <div class="col-md-6 col-md-offset-4">
        <button type="submit" class="btn btn-primary">
          Search
        </button>

 </div>
 </div

And that’s pretty much all there is to it. You can see again how having this extracted to a view partial keeps view code from being overwhelmed with spaghetti.

Ok, let’s go back to index.blade.php, the next line is:



@if(isset($results))

       @include('widget.searchresults')

       @else

       @include('widget.allrecords')

       @endif

So this is a if statement that checks to see if there are results from a search query. If $results, then we get the widget.searchresults partial, if we don’t have results from a search, we show the widget.allrecords partial instead.

I liked doing it this way because it is so readable and clean. The heavy, messy html has been extracted out to 2 different files. Let’s create searchresults.blade.php with the following:



 <div>
    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading">{{ $count }} Widgets Found </div>
        <div class="panel-body">
            <a href="/widget/create">
                <button type="button" class="btn btn-lg btn-success">
                   Create New
                </button>
            </a>
        </div>

        <!-- Table -->
        <table class="table">
            <tr>

                <th>Id </th>
                <th>Name </th>
                <th>Edit </th>
                <th>Delete </th>

            </tr>

           @foreach($results as $result )

                <tr>
                    <td>{{ $result->id }}  </td>
                    <td> <a href="/widget/{{ $result->id }}">{{ $result->widget_name }} </a> </td>

                    <td> <a href="/widget/{{ $result->id }}/edit">
                            <button type="button" class="btn btn-default">Edit </button>
                        </a> </td>
                    <td>{!! Form::model($result, ['route' => ['widget.destroy', $result->id],
                       'method' => 'DELETE'
                       ]) !!}
                        <div class="form-group">

                           {!! Form::submit('Delete', array('class'=>'btn btn-danger', 'Onclick' => 'return
                           ConfirmDelete();')) !!}

                        </div>
                       {!! Form::close() !!}
                    </td>
                </tr>
           @endforeach

        </table>

        <div>

        </div>
    </div>
 </div>

This is a basic Bootstrap panel with a table popped inside. You can see in the panel-heading that we echo a $count variable sent from the controller to let us know how many results we have.

Then we have a create button:



 <a href="/widget/create">
                <button type="button" class="btn btn-lg btn-success">
                   Create New
                </button>
            </a>

This route has already been provided by the Route Resource from our previous Route Resource tutorial.

Next we get the table heading:



 <!-- Table -->
        <table class="table">
            <tr>

                <th>Id </th>
                <th>Name </th>
                <th>Edit </th>
                <th>Delete </th>

            </tr>

You can see we are going to have an id column, a name column, an edit column, and a delete column.

Next we have the main part of the table:



@foreach($results as $result )

                <tr>
                    <td>{{ $result->id }}  </td>
                    <td> <a href="/widget/{{ $result->id }}">{{ $result->widget_name }} </a> </td>

                    <td> <a href="/widget/{{ $result->id }}/edit">
                            <button type="button" class="btn btn-default">Edit </button>
                        </a> </td>
                    <td>{!! Form::model($result, ['route' => ['widget.destroy', $result->id],
                       'method' => 'DELETE'
                       ]) !!}
                        <div class="form-group">

                           {!! Form::submit('Delete', array('class'=>'btn btn-danger', 'Onclick' => 'return
                           ConfirmDelete();')) !!}

                        </div>
                       {!! Form::close() !!}
                    </td>
                </tr>
           @endforeach

        </table>

Obviously, each pass of the foreach loop creates the table rows. You can see the Blade syntax in the td tags. For the delete button, we actually have a form because for security purposes, delete has to come via post, not a get request.

Also note, the @foreach loop is using the $results object that is returned from our search method in the WidgetController.

So that is the interesting part of that view partial.

Next we go back to index.blade.php to the call to include allresults.blade.php. Since we have not made that partial, let’s do that now. Create allresults.blade.php with the following:



 <div>
    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading">{{ $count }} Widgets </div>
        <div class="panel-body">
            <a href="/widget/create"> <button type="button" class="btn btn-lg btn-success">
                   Create New </button> </a>
        </div>

        <!-- Table -->
        <table class="table">
            <tr>

                <th>Id </th>
                <th>Name </th>
                <th>Edit </th>
                <th>Delete </th>

            </tr>
           @foreach($widgets as $widget )

                <tr>
                    <td>{{ $widget->id }}  </td>
                    <td> <a href="/widget/{{ $widget->id }}">{{ $widget->widget_name }} </a> </td>

                    <td>  <a href="/widget/{{ $widget->id }}/edit">
                            <button type="button" class="btn btn-default">Edit </button> </a> </td>
                    <td>{!! Form::model($widget, ['route' => ['widget.destroy', $widget->id],
                       'method' => 'DELETE'
                       ]) !!}
                        <div class="form-group">

                           {!! Form::submit('Delete', array('class'=>'btn btn-danger', 'Onclick' => 'return ConfirmDelete();')) !!}

                        </div>
                       {!! Form::close() !!} </td>
                </tr>
           @endforeach
        </table>
        <div>

           {!! $widgets->render() !!}

        </div>
    </div>
 </div>

This is very similar to the searchresults partial, except we are using a $widgets object instead of $results. The other difference is that we include:



  {!! $widgets->render() !!}

This for the pagination method that returns the results in groups of 10 records per page. Since we now have the allresults.blade.php separated out as a partial, we can refine it how we wish.

Ok, let’s go back to index.blade.php. For easy reference, let’s look at the content section:



@section('content')

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

   @include('widget.noresults')

    <br>

   @include('widget.searchform')

   @if(isset($results))

       @include('widget.searchresults')

       @else

       @include('widget.allrecords')

       @endif

@endsection

Ok, we wrap it up by using the @endif tag and then the @endsection tag.

The last part of index.blade.php is a little piece of javascript that we use to put an alert on the delete button, so that users don’t accidentally delete records by clicking the button:



@section('scripts')
    <script>

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

    </script>

@endsection

You can see we are using the scripts section, which will get injected into @yield(‘scripts’) in the Master page. You don’t have to put the actual script in here, it could easily be a call to public/js folder, if that is the name and path of where you keep your javascript files.

Anyway, that wraps up our index.blade.php and related view partials. All we have left is create.blade.php, show.blade.php, and edit.blade.php.

Let’s start with create.blade.php:



@extends('layouts.master')

@section('title')
    <title>Create a Widget </title>
   @endsection

   @section('content')

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

        <h1>Create a New Widget </h1>


        <hr/>

       @include('errors.errors')


       {!! Form::open(array('url' => '/widget', 'class' => 'form')) !!}

        <!-- widget_name Form Input -->
        <div class="form-group">
           {!! Form::label('widget_name', 'Widget Name') !!}
           {!! Form::text('widget_name', null, ['class' => 'form-control']) !!}
        </div>

        <div class="form-group">

           {!! Form::submit('Create Widget', array('class'=>'btn btn-primary')) !!}

        </div>

       {!! Form::close() !!}



       @endsection

So this is a very simple form with one input. We are using Bootstrapper’s form helper to open the form:



{!! Form::open(array('url' => '/widget', 'class' => 'form')) !!}

Note that we’re using the {!! !!} which doesn’t escape HTML because we want it to print the form html. It’s all incredibly easy to understand.

Next is the edit.blade.php file, which we need to make now:



@extends('layouts.master')

@section('title')
    <title>Edit a Widget </title>
   @endsection

   @section('content')

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

        <h1>Update {{ $widget->widget_name }} </h1>


        <hr/>

       @include('errors.errors')


       {!! Form::model($widget, ['route' => ['widget.update', $widget->id],
       'method' => 'PATCH',
       'class' => 'form',
       ]) !!}

        <!-- widget_name Form Input -->
        <div class="form-group">
           {!! Form::label('widget_name', 'Widget Name') !!}
           {!! Form::text('widget_name', null, ['class' => 'form-control']) !!}
        </div>

        <div class="form-group">

           {!! Form::submit('Update Widget', array('class'=>'btn btn-primary')) !!}

        </div>

       {!! Form::close() !!}

       @endsection

This is almost the same as the create.blade.php partial, but we use the Bootstrapper form helper to do a form model binding:



{!! Form::model($widget, ['route' => ['widget.update', $widget->id],
       'method' => 'PATCH',
       'class' => 'form',
       ]) !!}

So this will put the old value of widget_name in the form for reference. Also note, the method is set to PATCH, which is not supported by HTML, but Laravel makes the conversion for us.

The first parameter of the model method is the model, in this case $widget. Then we get the route, along with the model id, in this case $widget->id.

And now to finish up our Views tutorial, we will create the show view:



@extends('layouts.master')

@section('title')
    <title>{{ $widget->widget_name }} </title>
   @endsection

@section('content')
   {!! Breadcrumb::withLinks(['Home' => '/', 'Widgets' => '/widget', $widget->widget_name => $widget->id]) !!}
    <br>
    <div>
        <div class="panel panel-default">
            <!-- Default panel contents -->
            <div class="panel-heading">{{ $widget->widget_name }} Widget </div>
            <div class="panel-body">
                <a href="/widget/create"> <button type="button" class="btn btn-lg btn-success">
                       Create New </button> </a>
            </div>

            <!-- Table -->
            <table class="table">
                <tr>

                    <th>Id </th>
                    <th>Name </th>
                    <th>Edit </th>
                    <th>Delete </th>

                </tr>


                    <tr>
                        <td>{{ $widget->id }}  </td>
                        <td>{{ $widget->widget_name }} </td>

                        <td>  <a href="/widget/{{ $widget->id }}/edit">
                                <button type="button" class="btn btn-default">Edit </button> </a> </td>
                        <td>{!! Form::model($widget, ['route' => ['widget.destroy', $widget->id],
                           'method' => 'DELETE'
                           ]) !!}
                            <div class="form-group">

                               {!! Form::submit('Delete', array('class'=>'btn btn-danger', 'Onclick' => 'return ConfirmDelete();')) !!}

                            </div>
                           {!! Form::close() !!} </td>
                    </tr>

            </table>

        </div>
    </div>

@endsection
@section('scripts')
    <script>

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

    </script>

@endsection

You can see that we are again using the small piece of javascript as an alert. You should probably extract that out to separate file to avoid duplication. I will leave that for you to implement.

This is pretty much like our allresults.blade.php file, except we don’t have a foreach loop because there is only going to be one row of results.

The $widget object holds the correct model instance from the show method in the WidgetController.

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.

Master Pages in Laravel 5.1

Access all tutorials in sprocket icon.

August 1, 2015 from author Bill Keck.

Working with Blade as a template engine for Laravel is pure pleasure. It’s simply the best and most intuitive templating engine out there.

So you probably already know that a blade file is named something.blade.php, so if for example, you are creating an index page, you would name it index.blade.php.

If you need a refresher on blade, just check out the docs in Laravel.

Ok, so we’re just going to focus on the master page. A master page is a page intended to hold parts of your HTML that will be common to all of your pages. So to avoid code duplication, we create a master page to hold it so you don’t have to keep typing the same code over and over.

Your views folder resides in your resources folder, so we will add a folder inside of views named layouts. The path is resources/views/layouts. Inside the layouts folder, create a file named master.blade.php. This will be our master page.

I’m going to create a simple master page using Twitter Bootstrap. We’ll start with the top block:



<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
@yield('title')

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">


@yield('css')

</head>
<body> 

You can see the typical HTML necessities and we are pulling in our bootstrap css through a CDN call, which means we pull it in from a content delivery network, which also means most browsers will already have a copy cached, so it will load incredibly fast.

After that, you see:



@yield('title')

This is the spot where each page’s title will be injected. Then we have:



@yield('css')

So let’s talk for a moment about how a master page interacts with a view page. If for example, you had an index.blade.php file that you wanted to use in conjunction with the master page, you call the master page from within the view page like so:



@extends('layouts.master')

@section('content')

// page content goes here.

@endsection

You put your content in between the @section tags. Then behind the scenes, blade will inject the content section into the appropriately designated section on the master page will be tagged like so:



@yield('content')

Similarly, if you have custom css that you want to include on the master page from a view page, you can create a section like we did in our master page:



@yield('css')

Blade does all the assembly behind the scenes and it compiles the page, so you don’t incur overhead for using it. So this makes code separation a snap. And just as a refresher, I’ll cover the other way to pull in content into either your master page or an individual page, and that is to use a simple include like so:



@include('alerts.alert')

What that will do is look for an alerts folder and an alert blade file within it. So that’s a way to pull in a view partial that might contain form fields for example. These are the basics of blade. You can also check out a free video on this on Laracasts.

Ok, so getting back to our basic implementation of Bootstrap in our master page. Let’s look at the next block:



<div class="container">
<nav class="navbar navbar-inverse navbar-fixed-top">
 <div class="container-fluid">

   <!-- Brand and toggle get grouped for better mobile display -->
   <div class="navbar-header">
     <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">

       <span class="sr-only">Toggle navigation</span>
       <span class="icon-bar"></span>
       <span class="icon-bar"></span>
       <span class="icon-bar"></span>
     </button>
     <a class="navbar-brand" href="#">LaraTemp</a>
   </div>

   <!-- Collect the nav links, forms, and other content for toggling -->
   <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    
    
     <ul class="nav navbar-nav navbar-right">

         @if (!Auth::check())
       <li><a href="/auth/login">Login </a></li>
       <li><a href="/auth/register">Register</a></li>
         @else (Auth::check())
             <li><img class="circ" src="{{ Gravatar::get(Auth::user()->email)  }}"></li>
             <li class="dropdown">
                 <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">{{ Auth::user()->name }} <span class="caret"></span></a>
                 <ul class="dropdown-menu" role="menu">
                     <li><a href="/logout">Logout</a></li>

     </ul>
             </li>
             </ul>
       @endif
   </div><!-- /.navbar-collapse -->
 </div><!-- /.container-fluid -->
</nav>

@include('alerts.alert')

Ok, so I’m not really going to cover Bootstrap in detail. You can get all you need from the Bootstrap site. Also, I’m using an alerts partial, but I haven’t covered that in a tutorial yet, so you should probably cut that line if you are not doing something similar.

You can see that for a couple of menu items, we are doing an if statement to check and see if the user is logged in:



@if (!Auth::check())
       <li><a href="/auth/login">Login </a></li>
       <li><a href="/auth/register">Register</a></li>
         @else (Auth::check())
             <li><img class="circ" src="{{ Gravatar::get(Auth::user()->email)  }}"></li>
             <li class="dropdown">
                 <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">{{ Auth::user()->name }} <span class="caret"></span></a>
                 <ul class="dropdown-menu" role="menu">
                     <li><a href="/logout">Logout</a></li>

     </ul>
             </li>
             </ul>
       @endif

I’m also using a implementation of the Gravatar plugin, which I wrote a gravatar tutorial on, so you can check that if you want to use that.

Next we have the section where we are bringing in our content:



<div class="col-md-9">


@yield('content')


</div>

The next section we need is for our jquery and javascript:



</div>

   <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
   <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
 
  
   @yield('scripts')

You can also see that I’ve created a place to add scripts from the view page:


 
  
   @yield('scripts')

So for example if you had a view that used Bootstrap’s carousel and you needed to pull in additional javascript to set the delay between slides, then on the view you can use:


 
  @section('scripts')

// your javascript

@endsection

You can see from this that it makes it easy to control the dependency order. You bring in bootstrap js first, then the related js that you need for that page.

Next we just have the closing HTML tags and our basic master page is complete.



</body>
</html>

So now, whenever you want a view page to pull in the master page, you simply start the page with:



@extends('layouts.master')

Try to keep your code clean. If you have HTML errors, then blade can act wacky, and it can cause things to break. If you are seeing a blank white screen, it may be a syntax error.

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.

How to Use @inject in Blade in Laravel 5.1

Access all tutorials in sprocket icon.

June 12, 2015 from author Bill Keck.

In a previous tutorial, we looked at creating a laravel service provider for Laravel. A service provider is a beautiful aspect of the Laravel architecture, but in some cases, when you want to re-use a class in your views, you don’t need it.

Instead, you can use the @inject method in blade. It could work like this:



@section('content')

@inject('boom', 'App\Helpers\Contracts\RocketShipContract')

    {{ $boom->blastOff() }}

@endsection

Ok, so @section and @endsection are typical blade syntax to define where in the master page the ‘content’ will be placed. Then we can see we have the @inject method. The first parameter is the name of the local variable to hold the object, in this case I called it boom. You can call yours any name that falls within variable naming rules.

The next parameter is the class or contract you are instantiating. In this case, I’m calling a contract, because I have a service provider binding the contract to a concrete class. You can refer to that service provider tutorial for the exact reference.

Then in the dual curly brackets, which is again blade syntax to echo php, you see we are calling the blastOff method from the object instance variable $boom. The blastOff method simply returns a string of text. If you are curious why I chose boom, blastOff, and RocketShipContract, these were examples I was using in my service provider tutorial, which is a related subject. Check that out when you have a chance.

There’s an interesting example of @inject in a Laracast’s video where they use stats as an example, which is perhaps a closer to a real-world example.

Anyway, @inject offers you an easy alternative to service providers, allowing you to bring in reusable code that is not tied to a controller. As I’ve explained above, you can also use @inject in tandem with a service provider, when you want to call a contract instead of a concrete class.

Also note that you can place @inject outside of the @section where the object is being used. So if you want to perhaps place it at the top of the file, above the @extends line, you could do so. That might be more intuitive.


@inject('boom', 'App\Helpers\Contracts\RocketShipContract')

@extends('layouts.master')

@section('content')

    {{ $boom->blastOff() }}

@endsection

This looks really clean to me. That kind of flexibility is yet another reason to love the Laravel 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.

How to Create a Service Provider in Laravel 5.1

Access all tutorials in sprocket icon.

June 11, 2015 from author Bill Keck.

A beginner-friendly tutorial on building a service provider in Laravel 5.1.

I mentioned in my last blog that I love the Laravel 5.1 architecture, especially when it comes to service providers, which are the building blocks of your application. Configuration of an application can often be tricky task, depending on the framework you are using, but lucky for us, this is a fairly simple task in Laravel.

So let’s start by creating a route that we’ll use for demonstration purposes. Go to app/Http/routes.php and add the following route:



Route::resource('demo', 'DemoController');

Since we’re using Route::resource, we get index, show, create, edit, update, store, and destroy routes defined for us.

Now in perfect symmetry, we can use our artisan command line tool to create a matching controller for us. Type the following:



php artisan make:controller DemoController

Let’s open that file and change the index method to the following:



public function index()
{

    return view('demo.index');
}

Now let’s make a folder for the view in app/Resources/views named Demo, and in that folder create a view named index.blade.php like so:



@extends('layouts.master')

@section('content')
<h1>Demo Page</h1>
@endsection

In this case we are pulling in our master page, which I have in the layouts folder, master.blade.php. If you have a master page with another name, use that instead. If you have no master page, simply remove that extends line altogether, along with the @section statements.

Assuming you have set up your development environment to resolve your domain, when you hit the route yourapplication.com/demo, you should see the words Demo Page.

Ok, so now let’s create a service provider. This service provider isn’t going to do anything particularly useful. It’s just going to show you how to set one up.

Let’s start by creating a Helpers folder in our app directory. Then inside the Helpers folder, create a Contracts folder. Inside the Contracts folder, create RocketShipContract.php with the following contents:



<?php

namespace App\Helpers\Contracts;

Interface RocketShipContract
{

    public function blastOff();


}

As you probably are aware, an interface is a contract that enforces architecture. In order for a class to implement the interface, it must contain a public function named blastOff.

So why bother making a contract? Well, one of the amazing features in Laravel is that you can type hint the contract, and the service provider will return an instance of whatever concrete class you have bound to it. This creates an incredibly flexible and loosely coupled structure because you will be able to easily swap out implementations with a single line of code. We will see how this works in a little while.

First, let’s create the concrete class. In the app/Helpers folder, create RocketShip.php with the following:



<?php

namespace app\Helpers;

use App\Helpers\Contracts\RocketShipContract;

class RocketShip implements RocketShipContract
{

    public function blastOff()
    {

        return 'Houston, we have ignition';

    }

}

You can see our concrete class doesn’t do much, but we are mainly interested in how all this stitches together. You can decide for yourself what services you want to provide to your application.

Ok, now we need to create the service provider, which will bind the contract and the concrete class. Go to your command line and type the following:



php artisan make:provider RocketShipServiceProvider

Hit enter and it will create the class for you.

The new file is located in app/Providers. Go ahead and change it to the following:



<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Helpers\RocketLauncher;

class RocketShipServiceProvider extends ServiceProvider
{
    protected $defer = true;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('App\Helpers\Contracts\RocketShipContract', function(){

            return new RocketShip();

        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['App\Helpers\Contracts\RocketShipContract'];
    }

}

So let’s look at the pieces:



<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Helpers\RocketShip;

class RocketShipServiceProvider extends ServiceProvider
{

All fairly straightforward. We have our namespace, use statements and class declaration. When you create service providers, you will have to import the concrete class, in this case RocketShip, as I did with the use statement.

Next we have:



    protected $defer = true;

Setting the $defer property to true means this class will only be loaded when necessary, so the application runs more efficiently.

Next we have the boot function, which is just an empty stub, since we are not configuring anything.

Following that, we have the register method:



/**
 * Register the application services.
 *
 * @return void
 */
public function register()
{
    $this->app->bind('App\Helpers\Contracts\RocketShipContract', function(){

        return new RocketShip();

    });
}

You can see we are using the bind method to bind the contract to the concrete class. This is the one place within the service provider where the concrete method is defined. So if you wanted to change which the class the binding will call, it’s quick and easy. We will see this in action later.

Finally, we have the provides method:



/**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['App\Helpers\Contracts\RocketShipContract'];
    }

}

You need the above method if you are setting the $defer property to true.

All in all, this is a really simple class, which is part of the beauty of all this.

Ok, next we need to tell our application to look for this class, and we do that by adding it to the providers array in config/app.php.



        /*
         * Application Service Providers...
         */

        App\Providers\AppServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        App\Providers\RocketShipServiceProvider::class,

I included some of the other providers for reference, you can see our provider on the last line. Once you save this, you should be good to go.

So let’s go to our DemoController index action and modify it to the following:



public function index(RocketShipContract $rocketship)
{
        $boom = $rocketship->blastOff();

        return view('demo.index', compact('boom'));
}

So in this case, we are type hinting RocketShipContract and giving it an instance variable $rocketship. Laravel knows through the service provider that you actually want the RocketShip class because we bound it to the contract in the service provider. How cool is that?

Then we are simply calling the blastOff method and assigning it to a variable, which we will pass onto the view. Let’s modify the view:



@extends('layouts.master')


@section('content')

    {{ $boom }}

@endsection

You can see I’m using blade to echo the variable. So in your browser, you should see:



Houston, we have ignition.

So now to demonstrate ease at which you can swap out implementations, let’s create a second concrete class in our Helpers folder. Let’s call it RocketLauncher.php and place the following within it:



<?php

namespace app\Helpers;

use App\Helpers\Contracts\RocketShipContract;

class RocketLauncher implements RocketShipContract
{

    public function blastOff()
    {

        return 'Houston, we have launched!';

    }

}

You can see this is a lot like our RocketShip class, but our blastOff method is slightly different. So now to implement this, we simply change one line in our service provider in the register method:



public function register()
    {
        $this->app->bind('App\Helpers\Contracts\RocketShipContract', function(){

            return new RocketLauncher();

        });
    }


And also the use statement:



use App\Helpers\RocketLauncher;

And with those simple changes, we now have a different implementation bound to the contract and of course a new result in the browser.

Even though we did a super trivial example for this tutorial, you can see the benefits of this architecture. By coding to a contract instead of a concrete class, we gave ourselves flexibility and an easier way to maintain the code.

A couple of gotchas to look out for. You can’t rename the service provider without deleting and creating a new one from artisan because something behind the scenes causes the class not to be seen. It’s probably related to autoload. You can try running composer dump-autoload from the command line if you run into this type of situation. If that doesn’t work, delete the file and start over.

The other thing is don’t add the service provider to the config/app.php file until the last step. Having a class that doesn’t exist in there will mess up artisan.

The laravel framework has excellent documentation and you can read more about laravel service providers there.

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.

Validation Request – Laravel 5.1, how to handle validation on update?

Access all tutorials in sprocket icon.

May 24, 2015 from author Bill Keck.

Here is the quick answer for anyone who might be wondering how to handle validation on update in Laravel 5.  It seems like this is a common question, with lots of answers with verbose code.

However the solution is quite simple and concise.

The problem you can run into is that the validator requires the DB column to hold unique values, but when you are updating, you can’t pass validation unless you change the value for that field and you might not want to do that.

We’re going to look at this in the context of a request class, which  you would typically make to handle the validation rules for a form.  It’s a really cool feature of Laravel 5.

Inside the rules, you will have something like the following:


return [
    'name' => 'required|unique:mytablename,name,' . $this->mywildcard,
    'description' => 'required',
    'category' => "required|in:$range"
];

Ok, the basic validator rules you should be familiar with, if not check the guide.  

In the example above, we are supposing you want to store a name field in a table, generically referenced above as mytablename.  Obviously you will substitute that for the table where you store the name field, for example, if it were the users table, then it would be unique:users,name,

In order for this to work properly, we need to concatenate the id of the record, which is handed in through the route wildcard.  I’m just calling it mywildcard, in your case it could be id or any number of other things.  You just need to know it’s the value coming in from the route.

We use keyword $this, for example, $this->mywildcard or $this->id, etc., because the request object has this value.

Also note that the validation rule is within the single quotes and the id of the record is concatenated onto that outside of that string.  And that’s pretty much it. Laravel 5 does the rest.

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.