Laravel Posts
Laravel hasOneThough & Laravel hasManyThough RelationshipsLaravel

Laravel hasOneThough & Laravel hasManyThough RelationshipsLaravel
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
How to implement Laravel impersonateLaravel

How to implement Laravel impersonateLaravel
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.
Use Laravel localization key into your Javascript codeLaravel

Use Laravel localization key into your Javascript codeLaravel
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.
<script src="{{ asset('messages.js') }}"></script>
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');
UUIDs as Primary Keys with a Trait in Laravel 9Laravel

UUIDs as Primary Keys with a Trait in Laravel 9Laravel
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.
Why use UUIDs over regular IDs?
- 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.
How to integrate Paypal payment gateway with Laravel / PHP ?Laravel

How to integrate Paypal payment gateway with Laravel / PHP ?Laravel
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.
Difference between Eager Loading and Lazy LoadingLaravel

Difference between Eager Loading and Lazy LoadingLaravel
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.
Implement Bootstrap Laravel Livewire tablesLaravel

Implement Bootstrap Laravel Livewire tablesLaravel
It's 2022 and people are still using the old jquery tables with Laravel. As laravel have the livewire why do we have to use the jquery tables ??
In this tutorial, we are going to use the livewire tables and gonna see the benefits of it.
The main problem I see with Jquery Datatable is :
- Page will flicker when we do any search, as it will fire the server-side query and fetch results
- HTML Appending into JS for action column
- It's not easy to customize the row, we have to write the HTML into JS
The main benefits of using Laravel Livewire tables are:
- After searching results will be quickly updated on-page, without flickering
- As the Livewire table is JS less, Of course, you don't have to append HTML into it. you can do it via blade files :)
- You can easily customize the row and tables view by adding your custom blade views.
How to integrate Bootstrap Livewire tables?
For that we are going to use the following package :
https://github.com/rappasoft/laravel-livewire-tables
Install Package
composer require rappasoft/laravel-livewire-tables
Publish Assets
php artisan vendor:publish --provider="Rappasoft\LaravelLivewireTables\LaravelLivewireTablesServiceProvider" --tag=livewire-tables-config
php artisan vendor:publish --provider="Rappasoft\LaravelLivewireTables\LaravelLivewireTablesServiceProvider" --tag=livewire-tables-views
php artisan vendor:publish --provider="Rappasoft\LaravelLivewireTables\LaravelLivewireTablesServiceProvider" --tag=livewire-tables-translations
`
Choosing Bootstrap 5 theme
Into the published config file you can choose/change theme to bootstrap-5
return [
/**
* Options: tailwind | bootstrap-4 | bootstrap-5.
*/
'theme' => 'bootstrap-5',
];
Render the components
<livewire:members-table />
Create Component
namespace App\Http\Livewire;
use App\Models\User;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
class MembersTable extends DataTableComponent
{
protected $model = User::class;
public function configure(): void
{
$this->setPrimaryKey('id');
}
public function columns(): array
{
return [
Column::make('ID', 'id')
->sortable(),
Column::make('Name')
->sortable(),
];
}
}
That's It :)
That's it, and you will see the bootstrap-5 Laravel livewire table. it have other lot's of fucntionality too, you can use or disable it as per your need.
Top Laravel packages that you need in 2022Laravel

Top Laravel packages that you need in 2022Laravel
What is Laravel?
Laravel is the most popular PHP framework right now to develop web applications, it offers a very easy environment and services for developers.
In this blog, we are going to know about the packages that we must have to use while developing any laravel application.
Best Laravel Packages
Here we are going to see some best and top laravel packages that will help you to optimize your application performance and it's also very useful while doing the development.
IDE Helper
Github: https://github.com/barryvdh/laravel-ide-helper
It's a very helpful package and saves lots of time for the developer.
It will generate the helper file which enables our IDE to provide accurate autocompletion while doing the development.
Laravel Debugbar
Github : https://github.com/barryvdh/laravel-debugbar
This is very helpful when we have to check the page performance, in sense of how many queries are firing on the specific page? , how many models are loading? etc.
We can show the total processing time of the page, and the query results time too. by using that results we can do some refactor to our code and make our application more optimized.
Spatie Medialibrary
Github : https://github.com/spatie/laravel-medialibrary
This package is very useful when we are doing file uploads. also, it allows us to upload files to the s3 (AWS) very easily by changing just the file system driver.
The main functionality it has is it allows us to associate files with the Eloquent models.
Spatie Role Permission
Github : https://github.com/spatie/laravel-permission
It's 2022 and still, lots of developers are using the custom roles/permissions management. they even didn't familiar that this package have capabilities to manage each role/permissions management with a specific Eloquent model too.
We can assign roles or permissions to the user model or even any model. later we can check it via the middleware that this package is providing.
Ziggy
Github : https://github.com/tighten/ziggy
Before using this package you must need to implement the named routes into your laravel application.
Normally people can just provide a hardcoded URL into the JS file while doing the AJAX calls. But with this package, you can use the route we are using in blade files.
This allows us to use the route()
helper method in the JS files.