Laravel Posts

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
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.

February 03, 20231 minuteMitesh MakwanaMitesh Makwana
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
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
How to integrate Paypal payment gateway with Laravel / PHP ?

How to integrate paypal payment gateway with Laravel / PHP ?

In this tutorial we are going to see to integrate the paypal payment gateway with checkout method using the Laravel.

We are going to use package : https://github.com/srmklive/laravel-paypal

Install the package

composer require srmklive/paypal:~3.0

Publish Assets

php artisan vendor:publish --provider "Srmklive\PayPal\Providers\PayPalServiceProvider"

Set Paypal credentials into config/paypal.php

return [
    'mode'    => env('PAYPAL_MODE', 'sandbox'), // Can only be 'sandbox' Or 'live'. 
    'sandbox' => [
        'client_id'         => env('PAYPAL_SANDBOX_CLIENT_ID', ''),
        'client_secret'     => env('PAYPAL_SANDBOX_CLIENT_SECRET', ''),
        'app_id'            => '',
    ],
    ......
    ......
];

Create Routes

routes/web.php

 Route::get('paypal-onboard', [PaypalController::class, 'onBoard'])->name('paypal.init');
 Route::get('paypal-payment-success', [PaypalController::class, 'success'])->name('paypal.success');
 Route::get('paypal-payment-failed', [PaypalController::class, 'failed'])->name('paypal.failed');

Create Controller

app\Http\Controllers\PaypalController.php

setCurrency('EUR');
        $provider->getAccessToken();
        $data = [
            "intent"              => "CAPTURE",
            "purchase_units"      => [
                [
                    "amount" => [
                        "value"         => 100,
                        "currency_code" => getCurrencyCode(),
                    ],
                ],
            ],
            "application_context" => [
                "cancel_url" => route('user.paypal.failed'),
                "return_url" => route('user.paypal.success'),
            ],
        ];

        $order = $provider->createOrder($data);

        return redirect($order['links'][1]['href']);
    }

    public function failed()
    {
        dd('Your payment has been declend. The payment cancelation page goes here!');
    }

    public function success(Request $request)
    {
        $provider = new PayPal();      // To use express checkout.
        $provider->getAccessToken();
        $token = $request->get('token');

        $orderInfo = $provider->showOrderDetails($token);
        $response = $provider->capturePaymentOrder($token);

        dump($orderInfo);
        dd($response);
    }
}

That's it. Enjoy.

September 01, 20221 minuteVishal RibdiyaVishal Ribdiya
Difference between Eager Loading and Lazy Loading

We often listen to the words "Eager Loading" & "Lazy Loading" in Laravel. but maybe some of how still don't know what that actually stands for.

What Lazy Loading means?

I worked with many projects that is developed by some other developers and the common problems in code I found us Lazy Loading queries everywhere.

To understand it more easily let's take one simple example.

Let's say There is Post model and Comments Model.

So basically post->hasMany('comments')

So let's say we are fetching 10 posts and now we want the comments of each post. what we will do is :

$post->comments()->get() (LAZY LOADING)

Lazy loading cause N+1 queries issues as every time we are fetching comments of each post and it will block the execution too for while as its queries from the DB.

What Eager Loading means?

Eager loading is very useful when we are working with large-scale projects. it saves lot's of execution time and even DB queries too :)

Let's take the above example to understand the Eager loading.

$posts = Post::with('comments')->get()

$post->comments (EAGER LOADING)

here when we retrieve the posts at that time we are fetching its comments too on the same query. so when we do $post->comments it will not again do query into DB or not even block execution as the comments are already there in model instance.

So this is how Eager loading saves your time and also prevents N+1 Query.

Hope that helps.

August 13, 20221 minuteVishal RibdiyaVishal Ribdiya