Laravel Posts

Laravel Jobs - How Jobs works in Laravel?

Out of 100 only 30/40 people know about Laravel jobs and how its works or where we can use it.

When there is a need to use it specifically or the senior team asked that "You have to use Laravel Jobs", generally then people come to the web and search :

  • "How Laravel Jobs works ?" Or "Laravel Jobs works in Local Environment?"

In this tutorial, we are going to understand the basic functionality of jobs and their usage in simple words without any complex examples.

What is a Job?

Jobs generally contain a portion of code that runs in the background without blocking any other code.

You first need to create a job and you can write a portion of code into it.

Then you have to dispatch that job.

How Job works?

Let's say we want to send emails to 100 users. In general, terms what we do is: Execute a loop over each user and send emails one by one.

That will definitely take time and we also have to wait for the response.

Overcome that issue by using jobs.

First, we need to create a job that accepts 10 users and sends emails.

Now we will execute a loop over 100 users, so basically we have to dispatch the job 10 times.

So basically 10 times jobs will be dispatched and immediately we will get a response, as jobs run in the background without waiting for any response.

Hope its more clear now.

February 04, 20231 minuteVishal RibdiyaVishal Ribdiya
How to implement Paystack payment gateway in laravel application

How to implement Paystack payment gateway in laravel application

Paystack is the most popular payment gateway in Africa. Paystack has supported ZAR currencies.

It’s very simple to implement in your laravel application

Install package

 composer require unicodeveloper/laravel-paystack

Once Laravel Paystack is installed, you need to register the service provider. Open up config/app.php and add the following to the providers key.

 'providers' => [
     ...
     Unicodeveloper\Paystack\PaystackServiceProvider::class,
     ...
 ]

Register the Facade

 'aliases' => [
     ...
     'Paystack' => 
 Unicodeveloper\Paystack\Facades\Paystack::class,
     ...
 ]

Note: Make sure you have /payment/callback registered in Paystack Dashboard https://dashboard.paystack.co/#/settings/developer

Set Paystack credentials into config/paystack.php

 return [

    /**
     * Public Key From Paystack Dashboard
     */
    'publicKey' => 'PAYSTACK KEY',

    /**
     * Secret Key From Paystack Dashboard
     */
    'secretKey' => 'PAYSTACK SECRET KEY',

    /**
     * Paystack Payment URL
     */
    'paymentUrl' => 'https://api.paystack.co',

    /**
     * Optional email address of the merchant
     */
    'merchantEmail' => 'EMAIL ADDRESS',

 ];

Configure the route. Enter the code in your web.php file in the route directory

 //Paystack Route
 Route::get('paystack-onboard', [PaystackController::class, 'redirectToGateway'])->name('paystack.init');
 Route::get('paystack-payment-success',
    [PaystackController::class, 'handleGatewayCallback'])->name('paystack.success');

Then after create one controller PaystackController.php

 public function redirectToGateway(Request  $request)
     {
         try{
             $request->request->add([
                 "email"              => "Your email address",
                 "orderID"              => "123456", // anything 
                 "amount"              => 150 * 100,
                 "quantity"              => 1,                 "currency"              => "ZAR", // change as per need
                 "reference"              => Paystack::genTranxRef(),
                 "metadata"              => json_encode(['key_name' => 'value']), // this should be related data
             ]);

             return Paystack::getAuthorizationUrl()->redirectNow();
         }catch(\Exception $e) {
             return Redirect::back()->withMessage(['msg'=>'The paystack token has expired. Please refresh the page and try again.', 'type'=>'error']);
         }
     }

    public function handleGatewayCallback(Request  $request)
     {
         $paymentDetails = Paystack::getPaymentData();

 dd($paymentDetails);
 }

That's it. Enjoy.

January 26, 20231 minuteMitesh MakwanaMitesh Makwana
A look at what coming to Laravel 10

I am personally really excited about Laravel 10, are you also excited :) ?. the expected release date for Laravel 10 is 7th February 2023.

In this tutorial, we are going to cover new features and changes from Laravel 10.

Release Date

Laravel 10 will be released by 7th February 2023 and below is a list of annual release dates.

  • Laravel 9: February 8th, 2022
  • Laravel 10: February 7th, 2023
  • Laravel 11: February 6th, 2024

Drop Support for PHP 8.0

Laravel 10 dropping support for PHP <= 8.0, the minimum requirement to run Laravel 10 is PHP 8.1

Deprecations from Laravel 9

In Laravel 10 some of Laravel 9 methods will be deprecated, here is the list.

  • Remove various deprecations
  • Remove deprecated dates property
  • Remove handleDeprecation method
  • Remove deprecated assertTimesSent method
  • Remove deprecated ScheduleListCommand's $defaultName property
  • Remove deprecated Route::home method
  • Remove deprecated dispatchNow functionality

Native type declarations in Laravel 10 skeleton

In Laravel 10 the code userland generated by framework will contain the type-hints and return types.

Types will be added into latest PHP type-hinting features to Laravel projects without breaking backward compatibility at the framework level:

  • Return types
  • Method arguments
  • Redundant annotations are removed where possible
  • Allow user land types in closure arguments
  • Does not include typed properties

Any Many more

Hope that will be usefull.

January 09, 20231 minuteVishal RibdiyaVishal Ribdiya
Some Laravel tips that we must need to know

Some Laravel tips that we must need to know

1) Null safe operator

From PHP 8 you can use Null Safe Operator

How we are doing null checking code in PHP < 8.0

 $country =  null;

 if ($session !== null) {
     $user = $session->user;

     if ($user !== null) {
         $address = $user->getAddress();

         if ($address !== null) {
             $country = $address->country;
         }
     }
 }

PHP 8 allows you to write this:

 $country = $session?->user?->getAddress()?->country;

2) Ternary condition

We have used this ternary condition for checking null value

 isset($user->image) ? $user->image : null

We can short above condition like this

 $user->image ?? null

3) Clone a model

You can clone a model using replicate(). It will create a copy of the model into a new, non-existing instance.

 $user = App\User::find(1);
 $newUser = $user->replicate();
 $newUser->save();

4) Default Relationship Models

Laravel provides a handy withDefault() method on the belongsTo relationship that will return a model object even when the relationship doesn't actually exist.

 class Post extends Model
 {
     public function user()
     {
         return $this->belongsTo(User::class)->withDefault();
     }
 }

Now, if we try to access the $post->user relationship, we'll still get a User object even when it does exist in the database. This is known as the "null object" pattern and helps eliminate some of those if ($post->user) conditional statements.

For more information read Laravel withDefault() doc.

5) Save models and relationships

You can save a model and its corresponding relationships using the push() method.

 class User extends Model
 {
     public function phone()
     {
         return $this->hasOne('App\Phone');
     }
 }
 $user = User::first();
 $user->name = "Peter";
 $user->phone->number = '1234567890';
 $user->push(); // This will update both user and phone record in DB

Hope it will be helpful.

Thanks

December 30, 20221 minuteMitesh MakwanaMitesh Makwana
Laravel hasOneThough & Laravel hasManyThough Relationships

Laravel HasOneTHough & Laravel HasManyThough Relationships

We generally know about the 4 basics Laravel Relations ships that laravel provides:

Now we are going to see the major missing relationships that we are thinking are "Hard to use", but in real cases, it's needed while developing a project.

Even though I was thinking that HasOneThough and HasManyThough Relationships were will be hard to understand, I was wrong. it's really easy to understand.

Understanding HasOneThough

Let's say there is a Library that wants to know the book issuer's name directly, in this case, we generally do :

  • Fetch Books
  • Fetch its related issuer by using the HasOne Relation

What if I say I can directly access the issuer name into the Library model, yes we can achieve this by using the has one though.

Library
- id
- name

Book
- id
- name
- library_id

Issuer
- id
- name
- book_id
public function issuer() {
    return hasOneThough(App\Issuer, App\Book, library_id, book_id)
}

Understanding HasManyThough

Let's say in the same example that there are multiple issuers of the same books, we can achieve it as follow.

public function issuer() {
    return hasManyThough(App\Issuer, App\Book, library_id, book_id)
}

Hope it will be helpful.

Thanks

December 10, 20221 minuteVishal RibdiyaVishal Ribdiya
How to implement Laravel impersonate

What is user impersonate and why we use it in projects?

  • User Impersonate is useful when we want to login on behalf of admin user.
  • When we are a super-admin and we want to know about our users what they do in their account then this package is useful to check their activity.
  • If you implemented impersonate in your project then you need to maintain it because it may cause a security issue as well as user's privacy issue.

Here is a full documentation of laravel impersonate: https://github.com/404labfr/laravel-impersonate

So let's start with installing impersonate on your project copy the below code where we will install this package using composer.

 composer require lab404/laravel-impersonate

Add the service provider at the end of your config/app.php:

 'providers' => [
     // ...
     Lab404\Impersonate\ImpersonateServiceProvider::class,
  ],

Add the trait Lab404\Impersonate\Models\Impersonate to your User model.

Using the built-in controller

In your routes file, under web middleware, you must call the impersonate route macro.

 Route::impersonate();

 // Where $id is the ID of the user you want impersonate
 route('impersonate', $id)

 // Or in case of multi guards, you should also add `guardName` (defaults to `web`)
 route('impersonate', ['id' => $id, 'guardName' => 'admin'])

 // Generate an URL to leave current impersonation
 route('impersonate.leave')

Blade

There are three Blade directives available.

When the user can impersonate

 @canImpersonate($guard = null)
     <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
 @endCanImpersonate

When the user can be impersonated

 @canBeImpersonated($user, $guard = null)
     <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
 @endCanBeImpersonated

When the user is impersonated

 @impersonating($guard = null)
     <a href="{{ route('impersonate.leave') }}">Leave impersonation</a>
 @endImpersonating

That's it. Enjoy.

October 15, 20221 minuteMitesh MakwanaMitesh Makwana
Use Laravel localization key into your Javascript code

Convert all your localization messages from your Laravel app to JavaScript.

Generally, we cannot use the laravel localization key in its javascript. is that possible to use laravel localization in javascript?

Yes, now you can use laravel localization into laravel, thanks to the rmariuzzo/Laravel-JS-Localization package.

In this tutorial, we will learn how to use laravel localization in javascript, so let's get started.

Install the package

 composer require mariuzzo/laravel-js-localization

In your Laravel app go to config/app.php and add the following service provider:

Mariuzzo\LaravelJsLocalization\LaravelJsLocalizationServiceProvider::class

Usage

The Laravel-JS-Localization package provides a command that generates the JavaScript version of all your messages found in app/lang (Laravel 4) or resources/lang (Laravel 5) directory.

Generating JS messages

 php artisan lang:js

The resulting JavaScript file will contain all your messages plus messages.js in your public directory.

Link that js file into your main layout.

 

Documentation

Getting a message

 Lang.get('messages.home');

Getting a message with replacements

 Lang.get('messages.welcome', { name: 'Joe' });

Changing the locale

 Lang.setLocale('es');
October 05, 20221 minutePankaj MakwanaPankaj Makwana
UUIDs as Primary Keys with a Trait in Laravel 9

What are UUIDs?

UUIDs stands for Universally Unique Identifiers and are 128 bits values used to uniquely identify some record in our database. UUIDs are represented as a hexadecimal string split into five groups separated by hyphens.UUIDs are universally unique alphanumeric identifiers that are 36 characters long.

Instead of using auto-incrementing integers as your Eloquent model's primary keys, you may choose to use UUIDs instead.

Updating Migration File

It is a very important step to update our migration file, I want to use the UUIDs in my User class so I will make changes to my User’s migration class.

 $table->id();

to this:

$table->uuid('id')->primary();

If you are using a UUID primary key as a foreign key in another table, you need to change the column type to UUID, where the foreign key is defined. from this:

$table->unsignedBigInteger('user_id')->unsigned();

to this:

$table->uuid('user_id');

Using Trait in Our Model Class

you may use the Illuminate\Database\Eloquent\Concerns\HasUuids trait on the model.

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  use HasUuids;

  // ...
}

$user = User::create(['name' => 'John','email' => 'john@doe.com']);

$user->id; //72106479-5367-4853-9b44-b8b7a1e94f01

By default, The HasUuids trait will generate "ordered" UUIDs for your models. These UUIDs are more efficient for indexed database storage because they can be sorted lexicographically.

  • UUIDs are safer than using regular numeric IDs because they are not easy to spoof. Regular IDs make it easy to get information about the application, like how many users the application has.
  • Using UUID is a great solution for multi-tenancy applications.

I hope you will find this post useful.

September 20, 20221 minuteBhargav RanganiBhargav Rangani