How to send both HTML and Plain Text Password Reset Emails in Laravel 5.1

Laravel comes with an included Authentication system complete with password resets that saves you from the burden of having to set it manually on all your projects. In one of the apps I built, there have been reports of the password reset not making it to the end users. It just so happens that all email is being sent through a third party system which tracks sends and deliveries.

In this case, the emails were being sent and reported being delivered but the user kept claiming they didn’t receive it, the obvious culprit of it going to spam/bulk mail. In the research process, it was discovered that we only sent an HTML password reset without any text fallback. Maybe that was the reason?

This seemed like a simple improvement and could at least rule out that as a possibility. However, now all the mail is handled inside the Illuminate components and I couldn’t find any documentation on how to send both.

At this point, I started digging to try and see how Laravel is sending the email. Inside PasswordBroker I found an emailResetLink method which is how it is actually sent:

$view = $this->emailView;
return $this->mailer->send($view,

Now it’s just a matter of figuring out where “$view” came from and I didn’t have to look far. Inside the constructor it is injected:

public function __construct(TokenRepositoryInterface $tokens,
                            UserProvider $users,
                            MailerContract $mailer,
                            $emailView)

Next question is, where is the instantiated? Doing a project search for the class name lead me to the registerPasswordBroker in the PasswordResetServiceProvider. This pulls in from the config file:

$view = $app[‘config’][‘auth.password.email’];

Opening `config/auth.php` shows how it’s defined by default:

'password' => [
    'email' => 'emails.password',

Almost there. Going back to the mail documentation it shows you can send both with this call:

send(['html.view', 'text.view'], $data, $callback);

That means it’s just a matter of adjust the auth.password.email to be an array instead of the string:

'password' => [
    'email' => ['emails.password', 'emails.text-password]',
Don’t leave your users stranded–send both for an important email like this.

One of the benefits to Laravel is at almost every turn there is a simple way of solving a given problem and this is just one example. I hope by me outlining the steps I took to solve the problem it gives you insight into finding your own way around the next time you get stumped.

How to set up your Mac for local PHP Development

As a developer I spend countless hours on the computer. Over time I accumulate a ton of cruft. Everything from old forgotten files, unused apps, and worst of all hidden junk that has been installed by following some random tutorial.

This past weekend I decided it was finally time to wipe my Macbook’s hard drive and start fresh. I have used it daily for several years now and still had artifacts from when I used Mamp. Since then Vagrant has turned to my local server of choice and one of the reasons is how clean you can keep your machine by utilizing it.

After finishing the new Mac OS X install it felt like a new beginning. So clean, so minimal. I’ve missed that.

This go around I wanted to keep it as minimal as possible and only install things I know I need and use. This tutorial covers how I set up my Mac for local PHP Development. Continue reading “How to set up your Mac for local PHP Development”

Laravel and Stripe

Over the past few years, I’ve implemented Laravel and Stripe on multiple occasions. Everything from subscriptions to one-off purchases. When I started, Laravel Cashier wasn’t invented yet and it was a totally different beast, but now with Cashier it takes a lot of the pain away by having a simple API.

But with selling products and subscriptions there are many other aspects you need to think about and it’s easy to get intimidated thinking about all the features you need. Or worse, where to even start?

I wanted to share my knowledge on the subject and teamed up with an experienced author, W. Jason Gilmore, to create a new book on the subject, Easy E-Commerce using Laravel and Stripe. Jason has authored numerous books and has also built a 10,000+ product online store and a SAAS for the interior design and architectural industries.

We wanted to create a fun hands-on book taking you from the start of a project all the way through implementing product sales, digital downloads, and subscriptions.

The book is written around a fictional lawn care company that has hired you. But Mr. McDew, the owner of the company, is a stickler and wants to be sure you know what you are doing. So after each project phase he drills you with questions about the implementation, and if you answer correctly you get to move on to the next phase.

No web development book would be complete without sample code and we include many code samples, plus a complete companion project. This allows you to use it not only as a learning resource but you can run the app locally to test and play around with.

Some of the highlights include:

  • You will receive all of the source code to a real-world online store
  • Comprehensive, step-by-step instructions showing you how to integrate Stripe into your Laravel application using Cashier.
  • Learn how to integrate Stripe in a fun, entertaining, and unintimidating fashion by following along with the creation of a real-world project for a fictional company.
  • You’ll learn about many of the concepts central to building an online store, such as how to build a product management interface, and a one-time URL generator for downloading electronic products.

We also cover other Stripe features such as the “buy now” modal window, validating credit card forms, adding coupons and discounts, swapping subscriptions, and even implementing custom Stripe web hooks for sending emails.

Save yourself time and learn how to implement Laravel and Stripe today.

Laravel Query Debugging

I wrote a tutorial over on Scotch.io on debugging queries in Laravel. I go through three different ways, from using the ->toSql(), DB::listen, and the debugbar.

This is also my first time writing outside of my personal sites. So it was a lot of fun to see how the big sites operate.

How To: Validate an array of form fields with Laravel

Note: This tutorial is only relevant for Laravel 5.1 and lower. Laravel 5.2 has improved how this works.

If you’ve used Laravel’s form validation for any length of time, then you know it’s a powerful system. It makes the tedious task of validation very simple while still keeping the door open for complex rules.

In this tutorial, I want to show you a simple and easy way of validating forms that contain dynamic fields. A common use case for these types of forms is when you would like to allow a user to add more fields to a form.

Continue reading “How To: Validate an array of form fields with Laravel”

8 Laravel Packages For Your Next Project

The best way to spread Christmas Cheer, is singing loud for all to hear.

Buddy The Elf

Since my singing is terrible, I’m going to spread developer cheer by posting my eight favorite Laravel packages of 2014. These are in alphabetical order.

Carbon

This is included in the Laravel core but it’s worth mentioning because of how much I use it. Dealing with dates has never been easier.

Debugbar

All the behind the scenes information you need to ensure your app is running smoothly and efficiently.

Envoy

Envoy allows you to run SSH commands on a remote system. I use it for everything from local tasks to deployments.

Laravel DomPDF

This makes creating PDF’s nice and simple by wrapping the DomPDF library in a Laravel familiar syntax.

Laravel Generators

Speed up your workflow with these time-saving generators. It includes commands for almost everything.

Laravel IDE Helper

If you use PhpStorm then this package is a must have. I use it on all my projects and it makes your IDE play nicely.

Intervention

Every project seems to have to deal with image uploads in one form or another. Intervention makes image uploading and processing a breeze.

Parsedown

I use this whenever I need to parse markdown. It is fast, consistent, and easy to use.


All the projects I worked on this year, Snappy and one or two side projects, were really focused and I didn’t have a chance to implement a lot of the other packages. Hopefully, that changes over the next year because the community has created so many. I’d love to have the time to explore all of them.

Thanks to everyone who created in 2014!

Did I miss your favorite? Share in the comments.

JavaScript Helper for Triggering Stripe Failures

Lately I’ve had to integrate Stripe a few times and I keep having to visit their test card page over and over to copy and paste failed cards. Today I finally had enough and threw together a little helper that you can add to a Laravel blade file.

With this when you view the credit card form you can open console and type stripeData. and have autocomplete of whatever failed message you want to test for.

I know this is super simple but it helped me so I think it’s worth sharing.

The Simplest Way To Use Laravel Blade And AngularJS Together

By default AngularJS and Blade conflict with the way variables are called. Both use a double curly bracket {{ var }} syntax. There are a few workarounds such as changing Angular’s or Blade’s delimiters but an easier method is available.

Inside blade prefix Angular echo variables with the at [email protected] symbol. Here is an example:

This will prevent blade from parsing it but will be correct when sent to the browser.

Nice and simple!

Single Page Laravel Application

Michael Calkins asked me on Twitter the following question:

I would love to see the processes and techniques you use when designing a SPA. UI/UX, API considerations, and those things.

I thought it was an interesting question and the answer could be a benefit to the community so I’m going to do my best to answer it by outlining how I setup a brand new single page Laravel application. My last two projects have been with BackBone but I’m not going to focus on the actual framework, more so, just the setup and techniques.

Directory Structure

First I setup my directory structure by putting all my files that need to be processed inside app/assets. Then sub folders for each major area such as javascript, styles (less/sass), vendor (bower or manually copied components), etc.

From here I used Grunt, Gulp, or whatever is the new hotness and setup all the processing tasks. This will output to the public directory and I recommend spending the time on setting up source maps from the beginning. This is something I wasn’t doing and it would be so nice to have now.

First Changes

I always use Blade templates and in my master layout.blade.php I set the following meta tags:

<meta name="env" content="{{ App::environment() }}">
<meta name="token" content="{{ Session::token() }}">

I use the environment as a flag for any features that should only be in production or for testing only in development. I typically use this for things like analytics tracking or in weird cases.

The token is used for CSRF when posting from your JavaScript. Here is an example app/javascripts/plugins/ajax.js:

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
  var token;
  if (!options.crossDomain) {
    token = $('meta[name="token"]').attr('content');
    if (token) {
      return jqXHR.setRequestHeader('X-CSRF-Token', token);
    }
  }
});

As you can see this just pulls in the token and is always included on any ajax requests.

API Considerations

For both Snappy and Wardrobe I put all my controllers in the app/controllers/api folder and these are only used for javascript communication. I do recommend keeping these very thin so you can easily reuse code in the future when you need a mobile app. 🙂

A side benefit of putting them all in their own folder is the ability to utilize Laravel’s routing and request filters:

Request::is('api/*')
Route::when('api/*’)

Here is an example of one of my controller edit methods:

public function putEdit($id)
{
  $response = $this->post->update(Auth::user(), Input::all());

  return $this->handleJsonResponse($response, ‘Your post has been saved’);
}

Then handleJsonResponse() is defined in the BaseController and simply finds out the type of response and returns based on this:

protected function handleJsonResponse($response, $success = 'It worked!')
{
  if ($response instanceof IlluminateSupportMessageBag)
  {
    return Response::json($response, 400);
  }

  return Response::json(['msg' => $success]);
}

This keeps everything really DRY and easy to maintain. Also by returning the validator it gets converted to JSON and is easily consumed in your JavaScript.

JavaScript

This area really depends on the framework you have chosen on how you set it up. I only have the following two tips:

  1. Pre-seed all your primary JSON.
  2. Abstract plugins

By pre-seeding all your primary models/collections this will save you on that initial load time of fetching all the records and getting the app up and running.

Plugins are a necessary evil. I recommend always wrapping them in your own code with a simple api that way it’s easier to replace out later.

In BackBone a common pattern is to use views for this and just instantiate it when you need it. Here is a good presentation that goes more in depth on this.

CSS

I’ve struggled writing good clean CSS. If I’m being completely honest a lot of times I end up with a mess on big projects. It starts off great but then a new feature here, a new feature there, and wham! a mess. 🙂

If I was starting a new app today I would follow an existing style guide such as the one GitHub published or Smacss.

Since I’m not a CSS wizard I do not want to steer anyone in the wrong direction. However, I do have one tip to share and that is use slightly obtrusive javascript. What this recommends is adding a js- class to all elements your JavaScript interacts with:

<a href=“#” class=“js-edit edit”>Edit</a>

On small apps this is over kill but if you plan on maintaining this for years to come this is very helpful for refactoring and noticing when selectors are used elsewhere.

UI/UX

I could be off base with this, but I feel the terms UI/UX are a little open for interpretation. If I ask 5 engineers to define it off the hip, they all would give me different answers.

To me this is the most important area of any application and I feel UI/UX is what drives emotion and leads people to an action. Most engineers are generally weak in this area. If thats you then your goal should be to get everything related to the design uniform and plan from the beginning for adjustments. This area is rarely static.

The design and usability is so important in any app. No matter if it’s open source or commercial this is where users spend 100% of their time. Users do not care about your code and all your fancy design patterns. They have a goal in mind and need the simplest and easiest way to achieve it. This is what makes or breaks a product. It’s also the hardest to get right.

The closer you are to the development of a feature the harder it is to notice little nuances. I’m no different. Anytime I complete a new feature I always ask for feedback before deploying. 9 times out of 10 the reviewer will spot something that I totally missed.

To reiterate, if you are week in this area get everything uniform and bring an expert in. If you don’t have the means of getting an expert then plan on spending lots of time thinking and getting feedback.

Is it really different?

I do not believe it’s that much different from building a “traditional app”. Instead of one you now have two, a backend for api endpoints and auth then the front-end or client for the end user.

Over a thousand words later I hope I’ve answered Michael’s question without opening up many more. 🙂 Nevertheless if you do have questions don’t hesitate to get in touch.