How to set custom payload/Claims on Laravel JWT?

The payload will carry the bulk of our JWT, also called the JWT Claims. This is where we will put the information that we want to transmit and other extra information about our token.

There are multiple claims that we can provide. This includes registered claim names, public claim names, and private claim names.

Public claims that we create ourselves like username, information, and other important information.

So I wanted to send user information with the token in my open source project Laravel AdminPanel which is in Laravel 5.6 and I’ve used “tymon/jwt-auth”: “2.0.x-dev“. In the Latest version of tymon/jwt-auth , they have changed the way to add custom claims and document is not completed yet.

we need to implement the interface JWTSubject to our User model.

class User extends Authenticatable implements JWTSubject{
public function getJWTCustomClaims()
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'picture' => $this->getPicture(),
'confirmed' => $this->confirmed,
'registered_at' => $this->created_at->toIso8601String(),
'last_updated_at' => $this->updated_at->toIso8601String(),

Please don’t forgot to import JWTSubject :
use Tymon\JWTAuth\Contracts\JWTSubject;

If we want to access custom claims we can do it as mentioned below.


Hope it helps.


What’s New in Laravel 5.5

Laravel 5.5 is scheduled to be released in August of 2017 and is slated for the next major and the LTS release. in every new release of the frameworks, there’s always some cool new features to let’s take a look at what’s new.

Next LTS :

After the version 5.1, the next Long Term Support release will be 5.5, which is expected to include two years of bug fixes and three years of security updates.

Laravel 5.5 will require PHP 7.0 :

PHP 7.0+ comes with lots of new developer features and speed improvement, which will considerably decrease the CPU load.

“vendor:publish” Gets a Prompt:

That means when you are running the command, now a prompt will ask you to select the provider or task. This gives the developer the liberty to publish only the ones that they need.

If you want to publish views, configs, migrations and other resources of all vendors, like the older version; you can use the “–all” or “–provider”  flags to bypass the prompt.

Fresh Migrations:

A new “migrate:fresh” Artisan command is being introduced. This is similar to the existing “migrate:refresh” option, however, rather than rolling back your existing migrations, it drops all tables and migrates them from start.

Streamlined Request Validation:

Laravel 5.5 will now let us create objects directly from the validated data which means you can pass the result directly to your model’s create or update methods.

It’s also possible to call validate on a request instance directly in Laravel 5.5.You also no longer need to pass the request as the first argument to the validator.

public function store()
$task = request()->validate([
'title' => 'required',
'body' => 'required'

return Task::create($task);

Frontend Presets:

You may now configure the initial boilerplate as per your liking. Laravel 5.5 brings 3 front end preset options: Bootstrap, Vue, React with Vue being the default.

And you can strip all of it and if you want to remove any existing front-end scaffolding, you can use below command.

php artisan preset none

Automatic Package Discovery:

If you’ve ever installed a Laravel package before, you most certainly were required to visit your `config/app.php` file to add a service provider and alias. This is what allows the package to bootstrap itself into your Laravel installation. In Laravel 5.5, however, packages can optionally perform these steps automatically.

In Laravel 5.4 and all versions before, pulling a Laravel package required registering its service providers and adding aliases in `config/app.php`. In Laravel 5.5 packages can optionally perform these steps automatically and adds the ability for packages to automatically register service providers and add aliases through the package’s composer.json files.

And when a package is removed via Composer, then everything related to the package is also removed.

Faster Email Layout Testing:

In all the previous Laravel versions, we had to send actual emails or use an email client like Mailtrap to test email layouts. In Laravel 5.5, however, we can now return a mailable class instance directly from any route. very Convenient!

Custom Validation Rule:

In Laravel 5.5, you’ll find a brand new App/Rules folder. The next time you require custom logic for a particular request attribute, You can create a custom rule.

php artisan make:rule CustomRule

Collection Dumping:

Debugging a complex collection pipeline can get a little tricky. Often, you’ll find yourself temporarily commenting out portions of code, as you want to confirm the dumped output. In Laravel 5.5, you’ll find two new helper methods on your collection instances: dump() and dd().

$tasks = Task::all();


This makes it easy to inspect the contents of the collection at each step. Note, however, that there’s a difference between calling dump() and dd() on a collection. dump() outputs the results at that moment and then continues processing while dd() stops the process immediately and dumps out the results

Model Factory Generation:

In Laravel 5.4, all model factories were contained within a single file. And when you want to construct a new factory then you need to copy and paste the one before it. Luckily in Laravel 5.5, there’s a simpler way. You can generate factory through below command and each of your Eloquent models will now have a respective model factory file.

php artisan make:factory TaskFactory

This will make a new file called TaskFactory.php in the database/factories folder. What even better is, you can also generate a factory while making a model.

Custom Blade “If” Directives:

If you are using repetitive checks within blade templates in your application then this feature will be very handy and clean. As now it is possible to abstract repetitive checks out of templates, leaving our templates looking cleaner and more readable. Checks like:

The logic for creating a custom blade directive goes inside the boot method of the AppServiceProvider class:

use Illuminate\Support\Facades\Blade;
class AppServiceProvider extends ServiceProvider
public function boot()
Blade::if('subscribed', function () {
return auth()->check() && auth()->user()->isSubscribed();

Auto-Registering Artisan Commands:

In Laravel 5.5, you’ll no longer be required to manually register your Artisan commands, unlike all previous versions. The framework will instead automatically scan the commands folder for you. That means you may now run

php artisan make:command FooCommand,

and then immediately trigger it. very Useful.

Higher Order Tap:

tap() method was introduced in Laravel 5.3 and got some power boosts in 5.4. The tap() helper function has now been supercharged to be even more flexible.

return tap($task)->update([
'title' => $title,
'body' => $body,

As we know Eloquent method update() and save() returns boolean value but with the use of tap() as above we can get task model with the output and then we can use that model in whatever way we like. very helpful.

The RefreshDatabase Trait:

In previous versions of Laravel, you were presented with two database-specific traits for your test classes: “DatabaseTransactions” and “DatabaseMigrations”. Sometimes it may be confusing to newcomers.

In Laravel 5.5, all of this has been streamlined. You’ll now find a single “RefreshDatabase” trait that automatically figures out automatically which DB reset strategy to use.

Please note though “DatabaseTransactions” and “DatabaseMigrations” traits are still available for backward compatibility.

Route Helpers:

In Laravel 5.5, two new helpful Route::view() and Route::redirect() is introduced. Think of these as shorthand for loading a view and performing a redirect, respectively.

Route::view('/welcome', 'welcome');

This route will map the welcome view to the /welcome path

Route::redirect('home', 'dashboard');

this route will redirect any requests made to /home to the /dashboard.

Toggle Exception Handling Within Your Tests:

When writing tests for your application, you may encounter situations when you don’t want Laravel to automatically catch and transform an exception. You can now disable exception handling on a test-by-test basis, via the $this->withoutExceptionHandling() method call.

Whoops is back:

Laravel 5.5 brings back “Whoops”- the error handling framework, which was used in version 4, and was removed from version 5.0. Whoops changes the appearance of the PHP exceptions.

In my opinion, error messages look better with this new handler and the fact that we get a screenshot with the line of code that resulted in the error makes debugging even easier As you can see in the image that it sports the lines of the file in which the error or exception occurred and traces back the operation till inception.

Cleaner Exception Rendering:

For previous Laravel versions, if we wanted to handle custom exceptions thrown in a specific way,  you had to check in the Handler class’s report or render method if a particular exception was thrown.

A more object-oriented approach would be to allow the exception to determine how to render itself.

In Laravel 5.5, A more object-oriented approach would be to allow the exception to determine how to render itself and it’s possible to specify what happens when a custom exception is thrown by creating a report() and render() method inside that exception class. very cleaner approach.

Other Misslanious changes:

One minor change is that if you forget to include the CSRF field in a form then it presents you with better inactivity error page. So, if you see something like that, then be sure that it’s related to CSRF.

There is another minor change that will help you in building APIs. Now you get a JSON stack trace rather than HTML markup if an error occurs. This makes it a lot prettier to look at rather than the ugly markup if you are using a tool like Postman.
Below are the few useful links, which will have all the latest features and improvements in Laravel 5.5


Happy Learning!

Roadmap To Learn PHP & Laravel

Recently, I got an opportunity to train new joiners at the Cygnet Infotech. And I found this very helpful blog post related to that.

Roadmap To Learn PHP & Laravel

Thanks to  @introwit for the blog post.

This roadmap lists the complete course from step 1 to the end that will help a beginner learn PHP in the correct order right from scratch understanding almost all aspects of the language.

To be up to date with Laravel, you can follow top 15 Laravel Heros. You will learn many tips and tricks which will helpful into your day to day development.

If you are ever stuck somewhere while learning, hit me up on twitter at @solaniviral and I will be glad to help you.

Happy Learning!

Laravel : Best Practices

There are Many PHP Frameworks Available And I’ve worked with Zend, CakePHP, CodeIgniter then I picked up Laravel in 2014 and with version 4.2. Trust me, I totally love it now.

Speaking about Laravel, it is simple and comfortable to use, suitable to start with writing the production code, and gives a great boost to a development process. One thing that I love about Laravel is that it’s built using the best practices used in programming available in the current times.

Here are some simple things worth having in mind when developing in Laravel:

  • Try to make use of your .env file to the max you can.
  • Don’t create tables or index directly via PHPMyAdmin or console. Use Database Migration to create table, add/alter any fields, and commit those to Git repository.
  • Don’t insert fake values directly into the database for testing purposes. Create Seeder files or user Model Factory to populate your database.
  • Prefer to use Artisan CLI more than manually creating stuff, it’ll fasten up your productivity.
  • Make sure to boost performance using some artisan commands:
    php artisan route:cache
    php artisan config:cache
    php artisan optimize — force
  • Try not to write closures into your routes.php file, instead move them to your controller.
  • Use Named based Routing.
  • Be careful with the naming conventions when creating custom classes and functions, especially with your Models. Laravel works on a principle such that, for a table named users, it would expect it’s model name to be User.
  • Try to make Validation Requests separately for each request.
  • Although PHP has a class named DateTime to help you when reading, writing, comparing or calculating with date and time. It is recommended that you use the Carbon Library for dealing with dates.
  • Always keep yourself updated with the latest version, Laravel is updating real fast, so keep up the pace.
  • Always use gulp, Laravel Mix for compiling your scripts and sass into minified version for better performance, Laravel did the basic housekeeping for you.

Feel free to add more to the list…

How to replace plain URLs with links in JavaScript or PHP?

Hello Friends

If you want to convert plain text in to URLs in JavaScript or PHP. This is good solution for you.

In PHP :

public function makeLinks($str)
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    $urls = array();
    $urlsToReplace = array();
    if(preg_match_all($reg_exUrl, $str, $urls)) {
        $numOfMatches = count($urls[0]);
        $numOfUrlsToReplace = 0;
        for($i=0; $i<$numOfMatches; $i++) {
            $alreadyAdded = false;
            $numOfUrlsToReplace = count($urlsToReplace);
            for($j=0; $j<$numOfUrlsToReplace; $j++) {
                if($urlsToReplace[$j] == $urls[0][$i]) {
                    $alreadyAdded = true;
            if(!$alreadyAdded) {
                array_push($urlsToReplace, $urls[0][$i]);
        $numOfUrlsToReplace = count($urlsToReplace);
        for($i=0; $i<$numOfUrlsToReplace; $i++) {
            $str = str_replace($urlsToReplace[$i], "<a target='_balnk' href=\"".$urlsToReplace[$i]."\">".$urlsToReplace[$i]."</a> ", $str);
        return $str;
    } else {
        return $str;

In JavaScript

function makeLinks(text) {
 var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
 return text.replace(exp,"<a target='_blank' href='$1'>$1</a>");

Hope it helps.

8 Things Productive People Do During the Workday

8 Things Productive People Do During the Workday


Forget about your job title or profession – everyone is looking for ways to be more productive at work. It’s time to set down your gallon-sized container of coffee, toss out your three-page to-do list, and put an end to those ridiculously long emails you’ve been sending.

Experiencing a highly productive workday can feel euphoric. But contrary to popular belief, simply checking tasks off your to-do list isn’t really an indication of productivity. Truly productive people aren’t focused on doing more things; this is actually the opposite of productivity. If you really want to be productive, you’ve got to make a point to do fewer things.

Harness your productivity by taking note of these eight things:

1. Create a smaller to-do list. Getting things accomplished during your workday shouldn’t be about doing as much as possible in the sanctioned eight hours. It may be hard to swallow, but there’s nothing productive about piling together a slew of tasks in the form of a checklist. Take a less-is-more approach to your to-do list by only focusing on accomplishing things that matter.

2. Take breaks. You know that ache that fills your brain when you’ve been powering through tasks for several hours? This is due to your brain using up glucose. Too many people mistake this for a good feeling, rather than a signal to take a break. Go take a walk, grab something to eat, workout, or meditate – give your brain some resting time. Achieve more productivity during your workday by making a point to regularly clear your head. You’ll come back recharged and ready to achieve greater efficiency.

3. Follow the 80/20 rule. Did you know that only 20 percent of what you do each day produces 80 percent of your results? Eliminate the things that don’t matter during your workday: they have a minimal effect on your overall productivity. For example, on a project, systematically remove tasks until you end up with the 20 percent that gets the 80 percent of results.

4. Start your day by focusing on yourself. If you begin your morning by checking your email, it allows others to dictate what you accomplish. Set yourself in the right direction by ignoring your emails and taking the morning to focus on yourself, eat a good breakfast, meditate, or read the news.

5. Take on harder tasks earlier in the day. Knock out your most challenging work when your brain is most fresh. Save your busy work – if you have any – for when your afternoon slump rolls in.

6. Pick up the phone. The digital world has created poor communication habits. Email is a productivity killer and usually a distraction from tasks that actually matter. For example, people often copy multiple people on emails to get it off their plate – don’t be a victim of this action. This distracts everyone else by creating noise against the tasks they’re trying to accomplish and is a sign of laziness. If you receive an email where many people are CC’d, do everyone a favor by BCCing them on your reply. If your email chain goes beyond two replies, it’s time to pick up the phone. Increase your productivity by scheduling a call.

7. Create a system. If you know certain things are ruining your daily productivity, create a system for managing them. Do you check your emails throughout the day? Plan a morning, afternoon, and evening time slot for managing your email. Otherwise, you’ll get distracted from accomplishing more important goals throughout the day.

8. Don’t confuse productivity with laziness. While no one likes admitting it, sheer laziness is the No. 1 contributor to lost productivity. In fact, a number of time-saving methods – take meetings and emails for example – are actually just ways to get out of doing real work. Place your focus on doing the things that matter most as efficiently and effectively as possible.

Remember, less is more when it comes to being productive during the workday.

What’s your secret to productive workdays?