Quantcast
Viewing all 1769 articles
Browse latest View live

Invisible reCAPTCHA Integration With Laravel

Image may be NSFW.
Clik here to view.

Invisible reCAPTCHA is an improved version of reCAPTCHA v2 (No CAPTCHA) developed by Google, and users now only need to click the button: “I’m not a robot” to prove they are human.

In Invisible reCAPTCHA, there is no longer an embedded CAPTCHA box for users to interact with. It’s totally invisible with only a badge showing on the bottom of the page so users your website know you are using this technology. (The badge can be hidden, but this is not recommended.)

Here is an example what it looks like if you’re using Invisible reCAPTCHA:

Image may be NSFW.
Clik here to view.

I created a simple package to help you integrate Invisible reCAPTCHA into your Laravel projects quickly and easily!

Invisible reCAPTCHA Installation

composer require albertcht/invisible-recaptcha

Next, add the ServiceProvider to the providers array in app/config/app.php.

AlbertCht\InvisibleReCaptcha\InvisibleReCaptchaServiceProvider::class,

Configuration

Before you set your config, you need to apply for your API keys on https://www.google.com/recaptcha/admin first.

While choosing the type of your reCAPTCHA, remember to choose invisible reCAPTCHA to make it work in the background.

Image may be NSFW.
Clik here to view.

After you’ve registered a new site, take your keys and add them to your .env file:

INVISIBLE_RECAPTCHA_SITEKEY={siteKey}
INVISIBLE_RECAPTCHA_SECRETKEY={secretKey}
INVISIBLE_RECAPTCHA_BADGEHIDE=false
INVISIBLE_RECAPTCHA_DEBUG=false

If you set INVISIBLE_RECAPTCHA_BADGEHIDE to true, you can hide the badge logo.

You can see the binding status of those CAPTCHA elements on browser console by setting INVISIBLE_RECAPTCHA_DEBUG as true.

reCAPTCHA Usage

Display reCAPTCHA in Your View

{!! app('captcha')->render(); !!}

With custom language support:

{!! app('captcha')->render($lang = null); !!}

Validation

Add 'g-recaptcha-response' => 'required|captcha' to rules array.


$validate = Validator::make(Input::all(), [ 'g-recaptcha-response' => 'required|captcha' ]);

Check out the invisible-recaptcha package for the documentation and code.


Rollbar Config for your Laravel App – Sponsor

Image may be NSFW.
Clik here to view.

Rollbar is an excellent error-monitoring service that I often reach for two reasons:

They have a very generous free tier of up to 5,000 events (errors) per month, which is ideal for newer companies and smaller projects.

They allow you to pass user data with your errors, meaning you not only know when and where an error happened but—just as importantly—who it happened to.

Rollbar just upgraded their PHP SDK to version 1.0, incorporating namespacing, installation via Composer, and several other features that folks have come to expect from modern PHP software. You could use this new SDK directly with Laravel, but Rollbar itself will refer you to an excellent, easy-to-use—though somewhat sporadically maintained—third-party wrapper.

The wrapper hooks right into Laravel’s existing error handling, but despite what the documentation says, you can actually spin up basic error-tracking simply by installing the package and adding your Rollbar API credentials. However, to take full advantage of Rollbar’s user data collection, you do need to add a few lines of code to the report() function within your App\Exceptions\Handler class:

use Auth;

function report(Exception $exception)
{
    if (Auth::check() && $this->shouldReport($exception) ) { // Confirm the authenticated user, and that the errors should be reported.
        $user = Auth::User(); // Store the user in a variable (I think it reads more cleanly)
        \Log::error($exception->getMessage(), [
            'person' => ['id' => $user->id, 'username' => $user->first_name . ' ' . $user->last_name, 'email' => $user->email] // Pass the exception message and user-specific data.
        ]);
    }
    parent::report($exception); // If no authenticated user, let Laravel report the exception anonymously as usual.
}

The first thing you need to do is confirm an authenticated user—if you try to pass user data without one, your app will throw a browser-based 500 error, and provide no feedback on what happened. Don’t forget to import your Auth facade, too!

Next, you need to double-check whether the exception should be reported at all. This function is extended from the parent Illuminate\Foundation\Exceptions\Handler class and checks that the exception cannot be found within the $dontReport array at the top of your App\Exceptions\Handler class. Without this, your app will start logging every error—including, for instance, when a form submission fails a validation check. That’s a surefire way to hit your 5,000 errors per month.

Then, with your authenticated user and reportable exception, you’re ready to pass our user’s info over to Rollbar. Rollbar requires, at a minimum, an ID, but also accepts an optional username and email values. In the example above, I’ve chosen to pass a concatenation of first and last name as my username, but as long as you’re passing a string, you do you.

Finally, if one of those two conditions fails, you can bail, and Laravel will handle the exception as normal.

Again, this is a great package and I—along with 385,811 other developers—am extremely grateful to the author for creating it. I hope these small tweaks will help you get greater utility both from the package—and from Rollbar itself.


Many thanks to Rollbar for sponsoring Laravel News this week through Syndicate Ads.

Partyline – A Package to Print to the Artisan Console From Anywhere

Image may be NSFW.
Clik here to view.

Partyline is a new package that allows you to output to the console from outside of command class. This allows you more control on how things are printed and is great for when you need to loop items and show progress or other insights.

Here is an example of a normal Command’s handle method that I grabbed from their announcement:

// Console command without Partyline
public function handle()
{
    $this->line('Updating the index...');

    Search::update(); // ¯\_(ツ)_/¯

    $this->line('Surprise! It is finished!');
}

Inside the Search update() method it’s difficult to pass back feedback and with Partyline this can now include the following:

class Search
{
    public function update()
    {
        Partyline::line('Updating the index...');

        $entries = Entry::all();

        $bar = Partyline::getOutput()->createProgressBar($entries->count());

        foreach ($entries as $id => $entry) {
            $this->index->insert($id, $entry);
            $bar->advance();
        }

        $bar->finish();
        Partyline::line('All done!');
    }
}

Check out the annoncement and the Github repo for more details on this package.

Learn how to Improve the performance of your Laravel app with Performant Laravel

Image may be NSFW.
Clik here to view.

Performant Laravel is a new free video course created by Chris Fidao that covers quick performance wins you can implement right now into your Laravel apps.

The course includes 12 videos that range from three minutes up to twenty minutes, which makes them the perfect size for binge watching during your breaks and here is a list of all the videos included:

  • The Optimize Command – Learn how the optimize command speeds up Laravel.
  • The Route Cache – Use the route cache to skip route compilation on each request.
  • The Config Cache – Use the config cache to reduce configuration parsing & see its caveats.
  • Eager Loading – Use eager loading and avoid the dreaded n+1 query problem.
  • Database Chunking – Reduce memory usage on queries returning lots of data.
  • MySQL Indexing I – Cover a sample application and the queries it makes.
  • MySQL Indexing II – Learn what a database index is & how to create a basic index.
  • MySQL Indexing III – Learn how to improve the app’s slow queries with indexes.
  • Object Caching I – Discuss and configure object caching.
  • Object Caching II – Add a naive implementation of caching.
  • Object Caching III – Use the Decorator pattern to add caching to our app.
  • Object Caching IV – Discuss ways to reduce memory usage in Redis.

As mentioned above the course is free but it does require a signup. So head over to Performant Laravel and start the free course and learn to improve the performance of your Laravel app.

The real-time community site Voten goes open-source

Image may be NSFW.
Clik here to view.

The real-time community site Voten that recently made its first public beta has just announced it’s now an open source project. Voten is powered by Laravel 5.4 and Vue.js so it could be a good project to learn from the source, contribute, and get involved with.

Voten’s source code can be found on Github and they’ve also made the /c/votendev channel to discuss the development side.

They also have a /c/laravel and /c/vuejs channel if you’d like to submit some of your own work.

Bring Laravel Collections to JavaScript with Collect.js

Image may be NSFW.
Clik here to view.

Collect.js is a port of Laravel Collections to JavaScript. It’s dependency free and makes working with arrays and objects easy.

Here is an example of utilizing the where method:

const collection = collect([
  {'product': 'Desk', 'price': 200},
  {'product': 'Chair', 'price': 100},
  {'product': 'Bookcase', 'price': 150},
  {'product': 'Door', 'price': '100'},
]);

const filtered = collection.where('price', 100);

filtered.all();

//=> [
//=>   {'product': 'Chair', 'price': 100},
//=>   {'product': 'Door', 'price': '100'}
//=> ]

As you can see, it’s almost a one to one map with the Laravel version and it even includes the fairly new Collection Tap method but it does have some differences when dealing with comparisons:

All comparisons in collect.js are done using strict equality. Using loose equality comparisons are generally frowned upon in JavaScript. Laravel only performs “loose” comparisons by default and offer several “strict” comparison methods. These methods have not been implemented in collect.js because all methods are strict by default.

You can install Collect.js through NPM.

npm install collect.js

For complete documentation and installation take a look at the GitHub repo or the NPM page.

Laravel.io Launches Its Next Version

Image may be NSFW.
Clik here to view.

The Laravel community project, Laravel.io, that includes a forum and Pastebin, launched a brand new version. The release features a new design, a new authentication system, and the entire codebase has been rewritten from scratch.

The entire portal is open source and can be used as both a learning resource and as a project to contribute too.

Once you login it features a new dashboard that gives you a quick overview of your stats:

Image may be NSFW.
Clik here to view.

Another feature is the forums use tags for categorization and it utilizes a markdown editor for replies.

Image may be NSFW.
Clik here to view.

Check out the new Laravel.io Community Portal and start contributing through helping answer questions or by committing code.

Coaster CMS

Image may be NSFW.
Clik here to view.

Coaster CMS is a Laravel powered CMS created by the full-service digital agency Web-Feet.co.uk. Being an agency, they specialize in offering solutions to a wide range of clients, and this is where Coaster CMS was born.

“With eight years of combined developer experience of multiple CMS systems led us to a belief that there was still a market out there for a “block based CMS system” that didn’t confuse a user when they logged in to manage content.”, said senior developer Daniel Chadwick, “We had a pretty strong set of core ideas that keeps Coaster tied to being flexible in development and simple for the end user.”

Coaster CMS made its first official launch in March of 2016 they released it as open source to give back to the community and give people a different CMS option. Since then, the project has grown, and they just released v5.4 which includes a new WordPress importer, a new theme, full page caching, and more.

Coaster CMS Administration Highlights

Image may be NSFW.
Clik here to view.
Coaster CMS Dashboard
Coaster CMS Dashboard
Image may be NSFW.
Clik here to view.
Coaster CMS Pages
Coaster CMS Pages
Image may be NSFW.
Clik here to view.
Coaster CMS Edit Page
Coaster CMS Edit Page
Image may be NSFW.
Clik here to view.
Coaster CMS Media Manager
Coaster CMS Media Manager

The admin also features an advanced permissions setup and unique time specific content versioning, which allows pages to show different content at different times of the day.

Coaster CMS Beacons

Beacons are something I haven’t heard of before and from the Coaster CMS site here is what they are:

A beacon is a small Bluetooth radio transmitter. Think of it like a small lighthouse: it constantly transmits a signal that devices can see. Instead of light, they emit a very short-range radio signal transmitted on a regular interval of approximately 1/10th of a second. A Bluetooth-equipped device like a smartphone can “see” a beacon once it is in range. Depending on both devices’ proximity, a smartphone can perform several different actions. It can update an indoor map with your location, open a lock, or even change the music in your house as you walk from room to room. Beacons are a key technology in connecting the power of the Internet to our everyday life.

The key to the power of Beacons is that they are ‘location aware’ meaning that the information they broadcast is tailored to their location. This means that the user experience is incredibly valuable as there is no need to sift through irrelevant data. The experience can also be very personal to the user, as mobile phones are very personal devices.

As an example, you could have a page dedicated to an event that your company will be attending and linked to a beacon at the conference stand. The, when people are on their phones near the stand, they would see the notification for the page. This would be perfect as a lead generation system where it could have a form on the page to get their information.

Another example is a museum or an art gallery. You could have content pages that are dedicated to an art collection or individual items; then people could find out more info from their phones.

Time Specific Versioning

Image may be NSFW.
Clik here to view.
CoasterCMS Versions

Time specific versioning is a unique feature that allows you to set up content that should be published at a specific date or time, or go advanced and have special content only appear on particular days of the week or times of the year.

Developer Friendly Features

Coaster CMS is also developer friendly, and you’ll feel right at home since it utilizes Laravel and has embraced Laravel’s tooling such as Blade, Mix, migrations, Artisan, etc. Plus it supports powerful features for creating themes, great documentation, and a robust blocks system that includes the following types:

  • String, Dates, and Links
  • Forms
  • Gallery
  • Images
  • Selects
  • Videos
  • Repeaters

With these different types, you can create some unique and powerful views.

Getting Involved

If you’d like to get involved with the Coaster CMS project, they have a growing and active Slack channel, the GitHub repo for pull requests, and would enjoy having more themes created if you are of the designer type.

You can download the CMS, try it out, and join the community all from the Coaster CMS site. Give it a try and add a new CMS to your arsenal.


Many thanks to Coaster CMS for sponsoring Laravel News this week.


Monica is a Laravel Powered Personal Relationship Manager

Image may be NSFW.
Clik here to view.

Monica is a new kind of CRM that is designed to organize interactions with your friends and family and it’s built on Laravel.

Monica allows people to keep track of everything that’s important about their friends and family. Like the activities done with them. When you last called someone. What you talked about. It will help you remember the name and the age of the kids. It can also remind you to call someone you haven’t talked to in a while.

Monica is available as a download from Github or a hosted edition that you can signup for on their website.

Email Notifications from Understand.io – sponsor

Image may be NSFW.
Clik here to view.

Built specifically for Laravel, Understand.io is a very powerful tool used by hundreds of developers to stay on top of their application’s health. In addition to performing live search and analysis on your log data, you can also set up custom alerts. Alerts can be used to automatically send a variety of notifications via email, Slack or a webhook when something important takes place in your application.

Understand has recently introduced a daily email digest, which will further help you to proactively monitor your web app. The daily email digest contains a summary of the total volume of events from the previous day and week. Also included is an incredible Anomaly Detector, which will automatically spot unexpected patterns and unusual activity in your logs, thereby surfacing issues without your intervention.

Understand.io helps you to keep your customers happy. Get started now with a free trial. Plans start from only $9 per month.


Many thanks to Understand.io for sponsoring Laravel News this week

DD and Dump Is coming to Collections in Laravel 5.5

Image may be NSFW.
Clik here to view.

Coming to Laravel 5.5 is two brand new methods on the Collections class that will make debugging easier than ever before. These are dd and dump.

Pretend you have a simple collection setup and are piping it through a few filters:

collect([1,2,3])->map(function($i){
    return $i * 2;
})->reject(function($i){
    return $i < 3;
});

Knowing what happens in each step of the chain is can be difficult and now you’ll have the option to either “dump” it out at a certain point, or “dump and die”. For example:

collect([1,2,3])->map(function($i){
    return $i * 2;
})->dump()->reject(function($i){
    return $i < 3;
});

dump() outputs the results at that moment and then continues processing, here is the results when running that code:

Collection {#181 ▼
  #items: array:3 [▼
    0 => 2
    1 => 4
    2 => 6
  ]
}

dd() on the other hand stops the process immediately and dumps out the results:

collect([1,2,3])->map(function($i){
    return $i * 2;
})->dd()->reject(function($i){
    return $i < 3;
});

And the results:

array:3 [▼
  0 => 2
  1 => 4
  2 => 6
]

These will be welcomed features in Laravel 5.5 and if you’d like to start using these today, Spatie released a 3rd party package named Collection Macros that includes both of these methods and a few additional helpers.

Laracon US Live Stream Tickets on Sale

Image may be NSFW.
Clik here to view.

Laracon US is once again offering tickets to the live stream plus early access to the recorded videos for $29.99.

Please note that the live stream feed connection information will be distributed the day of the conference. This ticket also includes early access to full video archives. Refunds are generally not distributed in the event of connection problems since early access to video archives is provided.

Tweetsnippet – A Curated List of Tips and Tricks posted on Twitter

Image may be NSFW.
Clik here to view.

Tweetsnippet is a new site created by Casper Sørensen that curates tech tips and tricks that are posted on Twitter and puts them all in one place so it’s easy to browse and find them later.

I asked Casper for the back story on this site and how it came about and what follows is his answer:

I tend to browse Twitter multiple times a day, and within the last a couple of months, I noticed a trend where prominent community people would tweet out these little useful snippets for various things – CSS, JavaScript, PHP etc. I would then either like their tweet or even retweet it and then forget about it.

So I thought to myself – if there is a side project that would be meaningful to actually build, and also build in a short time-span, this would be it! So I hammered the current version out in 2-3 days during my vacation, and decided that I would upload it no matter how satisfied (or not) I would be with it :).

Then I heard the North Meets South Web Podcast (Ep. 31) with Jacob Bennett and Michael Dyrynda and their two guests Caleb Porzio and Daniel Colbourne where they talked about how they saved these little snippets, and thought to myself: they are describing exactly the issues I had myself, so I figured I might as well share it even in its unfinished state.

The application is built on Laravel on the backend and a small bit of vanilla Javascript on the front-end. I am using the Twitter API to persist the tweets to my own database. That functionality is powered by Vue JS, which enables me to just paste in a URL and it then returns to me a nicely formatted preview of the Tweet that I can then save to my DB.

With more and more people sharing tips and tricks through social media I believe a site like Tweetsnippet would be a good one to bookmark.

Laravel V5.4.28 is now released

Image may be NSFW.
Clik here to view.

The Laravel team released V5.4.28 yesterday and it includes a few new useful features.

The first of these is a new array_random helper that allows you do something like this:

array_random(['one', 'two', 'three']);
// "two"

Or you can specify the number of random items you’d like returned:

array_random(['one', 'two', 'three'], 2);
// array:2 [▼
  0 => "one"
  1 => "three"
]

Another new feature is an unless method on the query builder and Collections which allows you to make your code more expressive. For example, on a Collection:

collect()->when(! true, function () {});
// is the same as:
collect()->unless(true, function () {});

For all the other changes I’ve included the full change log below:

Laravel v5.4.28 Complete Change Log

Added

  • Added avg() and average() as higher order proxies (#19628)
  • Added fresh() method to Eloquent collection (#19616, #19671)
  • Added ability to remove a global scope with another global scope (#19657)
  • Added Collection::intersectKey() method (#19683)
  • Support setting queue name via broadcastQueue() method (#19703, #19708)
  • Support default return on BelongsTo relations (#19733, #19788, 1137d86, ed0182b)
  • Added unless() method to query builder and collection (#19738, #19740)
  • Added array_random() helper (#19741, #19818, #19826)
  • Support multiple manifest files on mix() (#19764)

Changed

  • Escape default value passed to @yield directive (#19643)
  • Support passing multiple fields to different validation rule (#19637)
  • Only dispatch the MessageSent event if mails should be sent (#19690)
  • Removed duplicate / from public_path() (#19731)
  • Made ThrottlesLogins more customizable (#19787)
  • Support PostgreSQL insert statements with DEFAULT VALUES (#19804)

Fixed

  • Fixed BelongsTo bug with incrementing keys (#19631)
  • Fixed PDO return value bug in unprepared() (#19667)
  • Don’t use event() helper in Http\Kernel (#19688)
  • Detect lock wait timeout as deadlock (#19749)
  • Improved escaping special characters in MySQL comments (#19798)
  • Fixed passing email as string to Event::emailOutputTo() (#19802)
  • Fixed withoutOverlapping() not creating mutex (#19834)

Removed

  • Removed role attribute from forms in stubs (#19792)

A guide for prioritizing application errors

Image may be NSFW.
Clik here to view.

This tutorial brought to you by

Remove guesswork and save time prioritizing bug fixes

Bug fixes and building new features are always in competition with each other, and it’s common for teams to have a hard time deciding where they should spend their time when it comes to prioritizing these two conflicting, but equally important tasks.

One major problem is that prioritizing errors isn’t always clear. Figuring out how much negative impact a bug is really causing is important to answer because not all bugs are worth fixing.

That’s why having a solid workflow in place for prioritizing bugs is so important. In order to confidently allocate your engineering resources on bug fixes and feature building, you need to understand the scope of each application error, and its impact on your customers. Then you can definitively say particular bugs are high enough priority that they should be scheduled into a sprint alongside your work on building new features.

Here’s a best practices guide for managing the prioritization of software bugs.

Get setup with smart error reporting from the start

To get off on the right foot, be sure to invest some time in setting up a robust system for detecting errors and alerting your team. This will go a long way towards helping your team be proactive about bug fixes, and give them visibility into which errors cause the most harm. By thinking about your setup from the start, you’ll make it easier to prioritize the right bugs to fix down the road.

Proactively detect application errors

It’s quite common to hear of engineering teams who mostly find out about bugs and fix them when a customer complains. This is a negative experience for the customer, and for the ones who do complain, there are probably countless others who gave up and churned from your product.

Proactively detecting errors when they happen can solve this problem and provide a better experience for your users. You’ll also have insight into how widespread errors are, so instead of reacting to whatever appears to be the greatest pain based on complaints; you’ll actually be able to fix the most harmful errors.

Use intelligent alerting to cut down on noise

When it comes to prioritization, a great place to start is by making your alerts smarter. Alert fatigue is something all engineering teams should be wary of, so instead of receiving a notification every time an error happens, opt to receive alerts for:

  • New types of errors
  • Errors occurring frequently
  • Regressions
  • Error rate spiking

This way you can stay focused on errors you haven’t seen before, or ones that might have a greater impact on your customers.

Group errors by root cause for visibility into a bug’s impact

You can increase visibility into the impact of each error by aggregating errors by root cause. A long list of error instances is better than nothing, but it really doesn’t offer much clarity into how frequently a given error is occurring, or how many users are being affected – key indicators into an error’s impact.

Image may be NSFW.
Clik here to view.

By grouping like-errors together, the ability to assess an error is much easier because you can see exactly how many times an error happened. This visibility gives you the information you need to prioritize bugs effectively.

Consolidate application errors for a clearer view of impact

Modern applications are made up of various systems, often built in different languages and using different technologies. Errors are not limited to manifesting within the borders of just one part of your app — a bug in your frontend code could be caused by a bug happening your backend code. If error information is spread through various systems, piecing it together can be a challenge.

Image may be NSFW.
Clik here to view.

By bringing all your error reporting together in one place, you’ll be able to track bugs throughout your system and understand how widespread they are.

Focus your error inbox to keep it actionable

Now that you’ve configured error reporting to work for you, some simple actions for cutting down noise will help keep things actionable and bring focus to your prioritization efforts.

Train your system to understand which errors to ignore

There are some bugs you’ll never be able to fix, like bots spamming your application with nonsense form data and URLs. It’s a good idea to turn off notifications for this kind of activity by silencing these notifications. In Bugsnag, you can do this with the Ignore action and all future notifications for that error will be silenced.

Temporarily silence errors until they reach a critical level

There are also times when an error might be important to fix in the future if it becomes more prevalent, but until it reaches that level, you shouldn’t spend time thinking about it.

Image may be NSFW.
Clik here to view.

 

Rather than leaving those types of errors sitting in your inbox (which can take up mental space and detract focus from errors that need immediate attention) snooze notifications for them until they reach a critical threshold.

Prioritize the most relevant errors first

Once your system is setup and error noise reduced, proper workflow and strategies will help you prioritize the most relevant errors first.

Focus on user impact

One of the most important things to consider is how much of your user base is impacted by an error. Generally speaking, a bug that only affects one user is probably less of a priority than one which affects hundreds. Mapping errors to users, in combination with grouping errors by root cause, is essential to this. In Bugsnag, for example, we show you how many users were impacted by a bug, alongside the error frequency, and let you sort by these metrics, so you can immediately understand how widespread an error really is.

Image may be NSFW.
Clik here to view.

Focus on key areas of your code

Another prioritization strategy is selecting, in advance, certain areas of your code you want to monitor more closely. For example, you might want to monitor and prioritize bugs in the checkout portion of your application, or on the signup page, more urgently. You can do this by passing in custom diagnostic data and then filtering to view all the errors impacting this area of your code.

Watch for errors affecting VIP customers

Similar to focusing on key areas of your code, you can also watch for errors that impact your most valuable customers. You can pass in custom diagnostic data, like pricing plan, which will be attached to the error reports of all your customers. Then simply filter for customers on a specific plan level to view the errors they’ve experienced in your product.

Image may be NSFW.
Clik here to view.

Concentrate on the most important releases

Another way to make prioritization easier is to only view errors in the releases you’re most interested in, like your latest or maybe two latest releases. That way you can focus on fixing bugs in the newest versions of your application since many of your customers probably will have upgraded, making supporting older versions of your app less important.

For JavaScript applications, you can use this same concept to filter down by browser versions as hopefully most of your users will have updated to later versions of their browser.

Prioritize errors by moving them into your debugging workflow

Once you’ve identified the most important errors to fix, you’re not quite done yet. It’s important to then figure out what to do with them by getting them into your debugging process. Will you assign errors to your teammates directly from your application error monitoring tool, or will you create issues for them in your issue tracker? Be sure to have a debugging workflow in place to help you move forward with your prioritized errors and resolve them. Check out our collaborative debugging workflow guide for strategies to help you get started.


Using an application error monitoring tool, like Bugsnag can give you visibility into your errors so you can prioritize them effectively. With best practices for getting setup and a streamlined prioritization workflow, you’ll save time and remove any guesswork from dealing with incoming application errors.


Laravel 5.5 Pivot Casting

Image may be NSFW.
Clik here to view.

A new addition to Laravel 5.5 will add support for pivot table casts when inserting & updating data on an intermediate table model.

Currently, the $casts you set on a traditional model will work in both directions; any model that extends the Eloquent\Model class will look for a $casts property and convert the specified attributes to a data type when reading and writing. For example, from the documentation:

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
    * The attributes that should be cast to native types.
    * @var array
    */
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}

In Laravel 5.4, Taylor added the ability to define a $casts property on your custom pivot models as well, but it only applied those $casts when reading the data—no conversion was performed when inserting or updating an attribute.

For example, let’s say you have a Runner model and a Race model. One runner can have many races, and one race can have many runners. Let’s call our pivot model a RaceRunner, which will include a splits array with a varying number of individual lap times (depending on the length of the race, and stored in seconds) in addition to the required runner_id and race_id.

The splits array is serialized as JSON in the race_runner table, so if you defined splits as an array in the $casts of your RaceRunner pivot model, then the following will dump an array:

dd( $runner->pivot->splits );

// Example:
[
    'Lap 1' => 150,
    'Lap 2' => 163,
    'Lap 3' => 146
]

But when creating or updating the pivot model, you still have to cast it manually:

// Cast first...
$splits = $splits->toJson();

// ...then attach:
$runner->races()->attach($raceId, ['splits' => $splits]);

Now with Laravel 5.5, the $casts property on the Eloquent\Model and Eloquent\Relations\Pivot classes will behave the same. Laravel will “respect” your casts on both, whether you’re reading, inserting or updating data. This will make the attach, sync and save methods available to pivot models. Applying this new feature to our example above, the // Cast first... code is no longer necessary.

Homeboy Allows You to Automate Adding Sites to Homestead

Image may be NSFW.
Clik here to view.

Homeboy is a new package for Laravel Homestead that allows you to add a new local development site quickly. Once you run the command line tool, it will update your host file to point your dev domain, update your Homestead.yaml file to include mapping to for the new project and create a database mapping, and finally, it’ll re-provision Vagrant.

Here is a video they put together showing it in action:

A tool like Homeboy is useful if you have a lot of projects in development and makes using Homestead almost as seamless as Valet. You can find out more about Homeboy and installation instructions from the Github repo.

Free Wildcard SSL Certs are coming to Let’s Encrypt

Image may be NSFW.
Clik here to view.

Let’s Encrypt will release wildcard SSL certificate support in January 2018. This will ease the burden of adopting and deploying SSL in cases where multiple subdomains need SSL support. From the official announcement on July 6, 2017:

A wildcard certificate can secure any number of subdomains of a base domain (e.g. *.example.com). This allows administrators to use a single certificate and key pair for a domain and all of its subdomains, which can make HTTPS deployment significantly easier.

Wildcard certificates will be offered free of charge via our upcoming ACME v2 API endpoint. We will initially only support base domain validation via DNS for wildcard certificates, but may explore additional validation options over time. We encourage people to ask any questions they might have about wildcard certificate support on our community forums.

The Let’s Encrypt API simplifies automating the renewal and creation of SSL certificates. Last month Let’s Encrypt reached a milestone of issuing more than 100,000,000 certificates and wildcard certificates will be a significant step in achieving a “100% encrypted Web”.

A Roundup of Laravel Testing Resources and Packages

Image may be NSFW.
Clik here to view.

Testing code is one of the more challenging parts of programming, but luckily Laravel and some other tools are making it easier than ever. Research has even shown implementing a Test-Driven Development (TDD) approach can significantly reduce the number of bugs that make it to production. Testing provides many other benefits, like the freedom to refactor large parts of a system without (as much) fear of breaking things.

With all of the benefits of testing, it’s still challenging to continually test applications. If you are looking to start learning how to test Laravel applications or you want to expand your skills here is a list of great resources to help you:

The Official Documentation

Image may be NSFW.
Clik here to view.

The official Laravel documentation is arguably the most complete testing guide that ships with a PHP framework. Not only does the guide itself make it very easy to start testing Laravel applications, but the framework itself also provides essential tools that take away the excuses of not testing. The most important features to make testing easier—that ship with Laravel—include database migrations for testing, factories, and mocking/fakes.

This first resource is obvious, but those new to Laravel and testing applications, stop by the documentation first. As a companion to the documentation, watch the Laracasts video Laravel From Scratch: Testing 101 for an overview of testing Laravel.

Laravel Dusk

Image may be NSFW.
Clik here to view.

Laravel Dusk is a browser testing package that works with >= Laravel 5.4. The Dusk documentation is part of the official Laravel documentation, but it’s worth mentioning separately because it is a recent addition to the Laravel testing tools. Dusk doesn’t require Selenium but uses the standalone ChromeDriver—which ships with the package.

Dusk allows you to test dynamic JavaScript applications with convenient browser abstractions and PHPUnit assertions. Before Laravel 5.4 full browser testing automation wasn’t possible without third party packages. This is another example of the Laravel framework facilitating testing and making it convenient for developers to get started.

The Orchestral Testbench Component

Image may be NSFW.
Clik here to view.

The Orchestral Testbench package is a testing helper for Laravel package development. According to the readme file, the Orchestral Testbench package:

…is a simple package that has been designed to help you write tests for your Laravel package, especially when there is routing involved.

The Laracasts Laravel Behat Extension

Image may be NSFW.
Clik here to view.

Behat is the defacto tool for Behavior-Driven Development (BDD) in the PHP community, and this package can help you get started with Behat and Laravel quickly. Before Laravel Dusk was available, full browser testing automation was only possible with third party packages and tools.

Although Dusk is now available, Behat might be a tool you prefer for acceptance testing if you prefer the BDD flavor of testing with Cucumber. Laracasts provides a lesson on using Behat,Laravel 5 and Behat: BFFs, which will help you get started with Behat 3 and Laravel 5.

phpspec

Image may be NSFW.
Clik here to view.

phpspec is a tool for writing BDD Specifications in PHP. The interesting thing about phpspec is how it guides you through small steps in writing test specifications, then making them pass. Learning phpspec can open your mind to a new way of testing.

You can learn how to get started with the phpspec manual. Laracasts has an introduction video to compliment the documentation. phpspec is a great tool for testing any PHP project, including Laravel packages.

phpspec Laravel Extension

Image may be NSFW.
Clik here to view.

phpspec Laravel Extension helps you test Laravel applications with phpspec:

This extension provides you with a bootstrapped Laravel environment when writing your phpspec tests.

Learning phpspec is a prerequisite for using this package.

Let’s Build a Forum with Laravel and TDD

Image may be NSFW.
Clik here to view.

The Build a Forum with Laravel and TDD series is only available to subscribers, but a the time of this writing there are 58 lessons on building a forum with Laravel and Test-Driven Development. This is one of the most complete tutorials on testing with Laravel and TDD. Even if you exhaust the generous number of free resources first, this is a great way to learn more about TDD with Laravel.

Test-Driven Laravel

Image may be NSFW.
Clik here to view.

Test-Driven Laravel is a video series by Adam Wathan which provides a thorough look into testing Laravel applications. This course is not free, but as of this writing, you could still get early access. The course has many hours of courses with more still being added.

Adam Wathan initially gave a presentation on Test-Driven Laravel at ZendCon and then condensed his talk into a screencast you can watch online. We’ve also reviewed this course on Laravel News.

Spatie Laravel Packages

Image may be NSFW.
Clik here to view.

Spatie provides many Laravel packages, and they continue to ship new packages to the community. The packages contain a wealth of testing source code and are a good reference to help you learn how to test Laravel packages. Some packages have a dependency on the aforementioned Orchestral Testbench, providing you with some examples of using Testbench in action.

Spatie packages also have Continuous Integration with Travis CI (laravel-backup example). The murze.be blog provides Laravel tips and tricks on package development and new package announcements being released by Spatie.

The Ruby on Rails Tutorial Book

Image may be NSFW.
Clik here to view.

This resource is a bit of a wildcard. While not PHP or Laravel related, this free online book is chock-full of real-world testing examples you can apply to your projects. It starts picking up testing features in Chapter 3.3.

Even if you don’t care about Ruby or Rails, you will be hard-pressed to find better testing material on how to write web application tests, including the theory behind what to test and how to test it. You can follow along or just read through the material to get some great testing insight and inspiration.

Test Driven Development: By Example

Image may be NSFW.
Clik here to view.

Test Driven Development: By Example is considered by many a classic text on TDD. While the examples are not written in PHP, the book covers an expansive list of TDD patterns and practices and will provide beginners a good background on TDD with some practical examples.

Blade::if() Directives

Image may be NSFW.
Clik here to view.

A new Blade addition in Laravel 5.5 will add support for simplifying custom if statements in your views.

The syntax might something like this in your AppServiceProvider::boot() method:

use Illuminate\Support\Facades\Blade;

Blade::if('admin', function () {
    return auth()->check() && auth()->user()->isAdmin();
});

The new Blade::if() makes it convenient to abstract repetitive checks out of templates, making them more readable:

@admin
    <a href="{{ route('super.secret') }}">Secret Page</a>
@else
    Welcome Guest. <a href="{{ route('login') }}">Login</a>
@endadmin

In previous versions of Laravel, you would have to write a bit more code. For example, David Hemphill tweeted some really cool directives using this technique in Laravel 5.4:

Which is now simplified even more in Laravel 5.5:

Blade::if('prod', function () {
    return app()->environment('production');
});

You can also pass arguments to make the checks more dynamic:

Blade::if('env', function ($env) {
    return app()->environment($env);
});

Which would then look like this in your templates:

@env('production')
  <script src="some-prod.js"></script>
@endenv

If you want to learn more about Blade::if(), Laracasts has a video tutorial on it, and we look forward to seeing what you’ll come up with!

Viewing all 1769 articles
Browse latest View live