What Version of Laravel do I have Installed?

A common Laravel question is “What version do I have” and how can I find this? Laravel offers several ways of answering this question but the easiest is to run the following through the Artisan command line tool:

php artisan -V

This will return the version currently installed such as:

Laravel Framework version 5.4.22

Another place you can look is inside your code at the composer.lock file. Open it and search for “laravel/framework”, and then the next line will have the version:

"version": "v5.4.22"

Either of these two places will give you the information you need and is useful for quickly finding out what version of Laravel you are running.

Using Laravel Mix for Your WordPress Theme

Laravel Mix is a fluent wrapper around the webpack module bundler, and it provides common tools that help you compile CSS and JavaScript. It’s easy to work with, and although it comes baked into the Laravel framework, you can use it anywhere.

This site is using WordPress, and when I created the theme I used Mix to handle the asset compiling; it was simple to setup. Here is a quick overview of how I did it in four steps. Please note, you will need to have a recent version of Node and npm installed on your machine before continuing.

Step 1. Create the package.json File

The package.json file is required to get all the Node modules you’ll need. Create this package.json file in your theme’s directory and add the following to it:

{
  "private": true,
  "scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },
  "devDependencies": {
    "laravel-mix": "0.*"
  }
}

I pulled these from the Laravel repo and removed all the devDependencies except for laravel-mix.

From your terminal, run npm install and all the dependencies will be pulled down automatically.

For my theme, I decided to utilize Bootstrap, so I required it via the command line:

npm install bootstrap-sass --save-dev

Bootstrap also requires jQuery so pull it in:

npm install jquery --save-dev

Now it has all the dependencies, and we are ready to setup the webpack file.

Step 2. Webpack Mix

Next up, create a file webpack.mix.js in the same directory as your package.json and add the following:

const { mix } = require('laravel-mix');

mix.js('js/app.js', './')
   .sass('sass/style.scss', './');

What this is doing is first loading the laravel-mix Node module, then setting up the compile steps. One for the JavaScript and another for Sass.

The important part here is the paths in the second param. For example, WordPress expects a style.css file in the root of your theme and by specifying the path as ./, it’s telling Mix to save the compiled file to the correct location.

Step 3. Create Your style.scss File

The final step is to create your style.scss file and based on the paths above this will need to go here sass/style.scss. Create this file and add the following:

/*!
Theme Name:         dotdev 2017
Theme URI:          https://dotdev.co
Description:        Minimal theme based on nosidebar
Version:            1.0.0
Author:             Eric L. Barnes
Author URI:         https://dotdev.co/
Text Domain:        dotdev-2017

License:            MIT License
License URI:        http://opensource.org/licenses/MIT
*/

// Bootstrap
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";

Please note the heading section has a special comment. By opening the multiline comment with /*! this tells the Sass compiler the comment should be kept in the source even after compiling. WordPress uses this in your wp-admin themes section.

Finally, we import the Bootstrap styles from the node_modules directory, and everything should be set and ready to go. If you run npm run dev this should output a style.css with Bootstrap included.

Of course, you are free to add any additional Sass files you need for your theme, here are mine:

// Variables
@import "variables";

// Bootstrap
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";

@import "site/layout";
@import "site/home";
@import "site/sidebar";
@import "site/author";
@import "modules/post";
@import "media/media";

Step 4. Create an app.js

Now, to compile your Bootstrap JavaScript create a new file js/app.js and import Bootstrap:

require('bootstrap-sass');

Save this, and run npm run dev again. Now you should have a compiled app.js file in your theme root with all the Bootstrap JavaScript.

That is all that is required. After this, you’ll just want to get comfortable with the Laravel Mix commands.

Laravel Mix Commands

Laravel Mix provides a few helpful commands while you are developing your theme. Here is an outline for the main ones you will need:

npm run dev

Run dev compiles the assets but does not minify. Useful for seeing the full source.

npm run production

Run production compiles and minifies, ready for you to push to production.

npm run watch

This keeps a watch on your files and if any change, then it runs the dev command automatically.


Check the Laravel Mix documentation for a complete list of everything it can do. Pretty much everything is supported when you are using it outside of Laravel, except for the versioning which relies on an internal Laravel helper function.

I hope this helps you create your next WordPress theme.

Creating Unique Title Slugs with Laravel

When storing content in the database a typical pattern for retrieving it is to create a unique “slug” based on the title. This gives users and search engines a human-friendly way to access it through the URL.

For example, a typical URL might look like, site.com/post/1. The id in the URL gives no hints at what the content is about and is not user-friendly. Slugs, on the other hand, are designed to turn this into site.com/post/my-awesome-article

Creating slugs from an existing string is easy in Laravel as it includes a helper for just this use case:

$title = str_slug('My Awesome Title', '-');

The results of this would be a lower-cased string with a dash (-) separator between the words:

my-awesome-title

While this is a huge help it doesn’t account for situations where you have two pieces of content with the same title.

Laravel slug class

Let’s build a small utility class to handle creating unique slugs based on existing data so we can ensure that no two are the same.

For reference here is the full class:

What this does is give you a createSlug method that can be used in creating and editing by passing the existing record id.

Here is an example of generating for both:

// On create
$post->slug = $slug->createSlug($request->title);
// On update
if ($post->slug != $request->slug) {
 $post->slug = $slug->createSlug($request->slug, $id);
}

The Slug class itself is pretty simple. createSlug calls getRelatedSlugs which performs a single query selecting all the records that could possibly be a duplicate. Then uses the Laravel Collections class to see if it’s already used:

if (! $allSlugs->contains('slug', $slug)){
 return $slug;
}

If it still has a duplicate then it appends a number to the end and performs another check for uniqueness:

for ($i = 1; $i <= 10; $i++) {
    $newSlug = $slug.’-’.$i;
    if (! $allSlugs->contains(‘slug’, $newSlug)) {
        return $newSlug;
    }
}

Finally, if all the numbers are exhausted it just bails out by throwing an Exception.

By utilizing Laravel’s existing helpers and Collections generating unique title slugs is easy. With this implemented all that would be required next is a custom route and a query to pull out a single post by its slug:

Route::get('/post/{slug}', function(){
    $post = AppPost::where('slug', $slug)->firstOrFail(); 
});

Laravel Valet

Laravel Valet is a new developer environment for the Mac that configures your Mac to always run PHP’s built-in web server in the background when your machine starts.

It automatically maps any .dev domain to your folder structure using DnsMasq. For example, if your project folder is “new-blog-879” then hitting “new-blog-879.dev” in your browser will load this folder.

Valet helps reduce the barrier to entry for running a local PHP web server and runs with a small footprint. Perfect for those old machines with not much RAM.

It’s not meant to be a replacement for a virtual machine like Homestead, Vagrant, or the likes. Instead, it’s opinionated and perfect for spinning up those new ideas quickly.

My computer setup is a work desktop machine that sits in my office and runs Homestead and I use it from 8 AM to 5 PM every weekday. Then at night I play around with side projects or look at new packages on an old Macbook. This is where speed and the time savings that Valet offers is huge. Instead of spending ten minutes setting up a new site through Homestead I can instantly start working. Of course, when I say ten minutes it’s always longer because I easily get sidetracked. Now, however, I have no excuse, the server is ready and waiting for me to start working on my next big idea.

Let’s take a look at how Valet works by spinning up a sample Laravel app and going through the process.

Installation

Installation is simple and it does require Homebrew. You’ll need to install that and then install PHP 7:

brew install php70

Note: You may get a warning such as “No similarly named formulae found.” If you hit that install:

brew install homebrew/php/php70

Next install Valet from composer:

composer global require laravel/valet

Finally, run the installer:

valet install

The install only has to run once and it sets Valet’s daemon to launch when your system starts.

Your first Valet site

Now that Valet is installed, it’s time to test out our first site. I created a new folder to hold all my sites at “~/Sites”. cd into this directory:

cd ~/Sites

Next run the Valet park command:

valet park

The park command tells Valet this is the location where all your sites are and it then maps the URL to folders in this directory. To show you an example create a new Laravel app:

laravel new todoapp

Once it finishes installing visit todoapp.dev in the browser and you should be greeted with the Laravel 5 placeholder page.

Now any new sites added are automatically picked up by Valet and you change the URL in your browser.

Not everyone keeps all their projects in a single folder and you can “park” multiple folders. Just “cd” to another one and run park again to add additional.

Sharing Sites with Laravel Valet

There are times when you are working locally that you would like to share what you see with others. If you are not in the same location this can be troublesome.

Valet ships with a tool called ngrok so you can share with anyone in the world. Here is all that is required to share your site:

cd ~/Sites/todoapp
valet share

After running the command it automatically adds a URL to your clipboard to share with others and shows you an overview of Tunnel Status and HTTP requests:

By sharing sites this gives you an added bonus of being able to use the share URL to test webhooks from services like Stripe, Mailgun, etc. Perfect for local development when testing webhooks are usually tricky.

Sites outside of your parked directory

If you have sites in other places on your file system you can still utilize Valet but utilizing it’s “link” command.

cd ~/Ideas/zonda
valet link zonda

Now you can hit zonda.dev in the browser and this site will load.

If you ever want to see a list of linked sites Valet offers the following command:

valet links

Then if you ever want to remove one:

valet unlink zonda

Securing a Laravel Valet site with SSL

Valet uses plain HTTP by default and with the release of 1.1.9 you can now easily serve sites over HTTPS by running:

valet secure zonda

Then to revert back to HTTP:

valet unsecure zonda

This is all managed through Caddy Server.

Laravel Valet with MySQL or MariaDB

Of course, almost every project you build is going to need to utilize a database. The database setup is outside the scope of Valet but it’s simple to get started. The documentation recommends MariaDB and currently it is a drop in replacement for MySQL. So let’s set that up and just note that MySQL would be installed basically the same way.

Using homebrew run the following:

brew install mariadb

Then start the service:

mysql.server start

Finally, connect through Sequal Pro or your tool of choice:

The settings are as follows:

  • Host: 127.0.0.1
  • Username: root
  • Password: (leave empty)
  • Port: 3306

Laravel Valet Drivers

Drivers are a unique feature that let you run any type of PHP app. This is needed because different apps require different URL rewriting rules. Valet comes preinstalled with drivers for Laravel, Lumen, Statamic, WordPress, and CraftCMS.

If you are wanting to run a different app then you will need to create a new driver. The documentation is going to be the place to look for deeper instructions on this as each app is unique in their requirements.

Learning more about Laravel Valet

As I said earlier I’m very excited about Laravel Valet. It solves a legitimate pain point for a lot of developers and is simple to use. With the release of Valet, I’ve been able to ditch Mamp and get everything running quickly.

No more worrying about vhosts, fiddling with YAML files, or anything else. Stop the configuration madness and start developing as soon as the inspiration hits.

Laravel Spark

Laravel Spark, the Laravel package that provides scaffolding for subscription billing, is now officially released and available for everyone.

August of 2015 at the Kentucky Center hundreds of developers sat waiting as Taylor Otwell took the stage for the Laracon Keynote talk. He kicked if off talking about finding inspiration from the movie Jiro Dreams of Sushi.

“Jiro would dream of sushi, wanting to elevate his craft. One could assume this gives him a deep and satisfying meaning to life”, Taylor recalled, “we share a lot of the same characteristics, and one big item is flow.”

Flow, also known as the zone, is the mental state of operation in which a person performing an activity is fully immersed in a feeling of energized focus, full involvement, and enjoyment in the process of the activity.

Taylor continued by talking about how Laravel aims to make the pathway to flow as easy as possible by allowing you to focus on the app you are building, not the mundane boilerplate.

Some of the examples include Homestead as a development environment, Forge and Envoyer for production deployments, and all the other tools Laravel provides like Blade, Eloquent, and Elixir.

This lead to his newest creation Laravel Spark, which aims to make creating a working SaaS (software as a service) app painless.

The keynote continued going through a demo and announced the alpha would be available the following month. Then all went silent.

Having just launched Forge and Envoyer, Taylor knew how much of a burden building out subscription billing is. It needs a payment gateway, full member management, subscribing to plans, subscription swapping, subscription canceling, pro-rating, coupons, discounts, teams, invites, and that is just the bare minimum feature set. You also have to add routes, views, JavaScript, and more to get this all working.

What Spark does is combine all this into a single package that you can add to a Laravel app. Define your subscription plans, set your company address, add Stripe data, and deploy.

Development of Spark continued behind the scenes, and little teasers of the official version started being leaked to social media at the end of February. Then on March 3rd, Taylor announced the official release will not be free.

During the keynote, Spark was released as a free open source product, and this pivot caused a mix of both positive and negative reactions. Most were understanding of the change in direction.

The #sparkwatch teasers didn’t stop, and then a super specific launch date came out. April 19th at 10 AM CET. As that date started approaching Spark became feature complete and a beta launched Friday, April 15th.

The pricing is $99 for a single license and $299 for an unlimited. With one license you can develop as many sites as you want locally and it only goes into effect once you deploy to a server.

Laravel Spark First Impressions

As soon as the beta was announced, I grabbed a license and started building a fictitious app just to get an idea how it’s all setup and the benefits in using it.

The installation was straight forward. You have to clone laravel/spark-installer and add the spark executable to your $PATH, then run a register command with your license token. After that it’s just a matter of creating a new project:

spark new MyNewSparkApp

Note: By default this sets up Stripe as the payment gateway without the teams option. However, you can use pass a braintree or team-billing flag to use the different gateway, or add teams.

spark new MyNewSparkApp --braintree --team-billing

It automatically pulls down all the packages through Composer, asks if you want to install the NPM modules, and finally you finish off my running the migrations.

That is literally all it takes to get it installed.

The final step before fully testing it is to open the SparkServiceProvider and scroll through this file entering your settings. It has a section for your company name, address, phone number. Your billing plans. An array of developers emails that can access the admin. The ability to define your billing plans.

After installing and browsing around it does have a great base to begin your work with.

The design is based on Bootstrap so customizing the views should be straightforward. The JavaScript is powered by Vue.js and the customization primer gives instructions on how to add your own Components.

Laravel Spark Pricing

As mentioned earlier, the pricing is $99 for a single license and $299 for an unlimited. You do have to purchase a license before you can install it and then you can develop as many sites as you want locally. Once you deploy to a server, then that license becomes used.

The question is, is Spark worth $99? Having spent the last six months developing a billing system, I can say it is. If I tried to build out, everything Spark includes it would take me at least several weeks, and probably not be as good as what it provides. To answer the question, emphatically yes!

Another benefit for picking up a license, even if you aren’t in a position to need billing, is to use it as a learning tool. You can view the package and see how it’s put together, see how it utilizes Composer to sell commercial software, and even learn how the creator of the framework structures his routes, views, and JavaScript.

You can get a copy from the Spark website and check out the full documentation.