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.

JWTAuth::getPayload();
JWTAuth::getPayload()->get('first_name');

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 investigate.so 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();

$tasks
->dump()
->sorBy(‘title’)
->dump()
->pluck(‘title’)
->dump();

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

References/Resource:

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…