Laravel's post
How to delete record using Ajax in LaravelLaravel

How to delete record using Ajax in LaravelLaravel

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<script> let categoryUrl = '{{route('categories.index')}}'; </script>
$(document).on('click', '.delete-btn', function (event) { const id = $(event.currentTarget).data('id'); swal({ title: 'Delete !', text: 'Are you sure you want to delete this Category" ?', type: 'warning', showCancelButton: true, closeOnConfirm: false, showLoaderOnConfirm: true, confirmButtonColor: '#5cb85c', cancelButtonColor: '#d33', cancelButtonText: 'No', confirmButtonText: 'Yes', }, function () { $.ajax({ url: categoryUrl + '/' + id, type: 'DELETE', DataType: 'json', data:{"_token": "{{ csrf_token() }}"}, success: function(response){ swal({ title: 'Deleted!', text: 'Category has been deleted.', type: 'success', timer: 2000, }); $('#categoryTbl').DataTable().ajax.reload(null, false); }, error: function(error){ swal({ title: 'Error!', text: error.responseJSON.message, type: 'error', timer: 5000, }) } }); }); });
public function destroy($id) { $category = $this->categoryRepository->find($id); if (empty($category)) { Flash::error('Category not found'); return $this->sendError('Category not found.'); } $this->categoryRepository->delete($id); return $this->sendSuccess('Category deleted successfully.'); }
Setup Laravel Livewire with Basic Component ExampleLaravel

Setup Laravel Livewire with Basic Component ExampleLaravel
composer require livewire/livewire
... @livewireStyles </head> <body> ... @livewireScripts </body> </html>
php artisan make:livewire Summation
// app/Http/Livewire/Summation/php namespace App\Http\Livewire; use Livewire\Component; class Summation extends Component { public function render() { return view('livewire.summation'); } } // resources/views/livewire/summation.blade.php <div> ... </div>
<head> ... @livewireStyles </head> <body> <livewire:summation /> ... @livewireScripts </body> </html>
namespace App\Http\Livewire; use Livewire\Component; class Summation extends Component { public $value1 = 0; public $value2 = 0; public $sum = 0; public function mount() { $this->sum = 0; } public function render() { $this->sum = $this->value1 + $this->value2; return view('livewire.summation'); } }
<div> <input type="text" class="" wire:model="value1"> <input type="text" class="" wire:model="value2"> <input type="text" disabled wire:model="sum"> </div>
How to Integrate the Stripe Customer PortalLaravel

How to Integrate the Stripe Customer PortalLaravel
The Stripe Customer Portal is very useful for managing customer subscriptions like Upgrade, Downgrade, and Renew.
Customers can review their invoices directly and also check their history.
Portal billing setting
Do login into your stripe account
Navigate to the portal settings to configure the portal, and do below billing settings
Create Product
First of all, we need to create products. Follow the below process for creating products.
Click on the “Products” menu from the sidebar and click on the “Add Product” button on the top right corner of the products page and create a product.
Here is an example of how to create a product.
Create two or three products as shown below.
Select product In portal settings
If you want to allow your customer to change their subscription by an upgrade, downgrade, cancel or renew you need to set products in your portal setting.
Now navigate to customer portal settings again, in the Products section, you will find a dropdown “Find or add a product..”, click on it you will find the plan you have added, select the price of this product.
Don’t forget to save all these settings.
Then do the setup of your business information, also do branding settings in the “Appearance” section, and save it.
Once you are done with settings, you can preview the customer portal by clicking the Preview button beside the save button.
This will launch a preview of the portal so you can see how customers will use it for managing their subscriptions and billing details.
Integrate into Laravel
- Get you API keys
- Go to “Developers > API keys” here you will find your “Publishable key” and “Secret key
- Create customer using stripe dashboard or by API
- Create customer by Stripe API.
- First of all, you’ll need to set your stripe secret key. For development mode, you can use test mode keys, but for production, you need to use your live mode keys
\Stripe\Stripe::setApiKey('sk_test_YOUR_KEY');
$customer = \Stripe\Customer::create([
'name' => 'jenny rosen'
'email' => 'jenny.rosen@example.com'
]);
- Once you create a customer using stripe API, now you can create a billing session for that customer using stripe API.
- Create a billing session of the customer by API
\Stripe\Stripe::setApiKey('sk_test_YOUR_KEY');
\Stripe\BillingPortal\Session::create([
'customer' => 'cus_HnKDAQNjBniyFh',
'return_url' => 'https://example.com/subscription',
]);
You’ll get a response, like the below object:
{
"id": "pts_c5cfgf8gjfgf73m5748g6",
"object": "billing_portal.session",
"created": 453543534,
"customer": "cus_bGFsnjJDcSiJu",
"livemode": false,
"return_url": "https://example.com/subscription'",
"url":
"https://billing.stripe.com/session/{SESSION_SECRET}"
}
In the response body, there is a URL attribute:
Now redirect your customer to this URL immediately. For security purposes, this URL will expire in a few minutes.
After redirecting the customer to this URL, the portal will open and customers can manage their subscriptions and billing details in the portal. customers can return to the app by clicking the Return link on your company’s name or logo within the portal on the left side. They’ll redirect to the return_url you have provided at the time of creating the session or redirect URL set in your portal settings.
Listen to Webhooks
You must have a question, what is this Webhook!!!
It’s just an event, which will fire when a customer does any changes in his/her subscription in the portal, we can listen to this event in our app and make appropriate changes.
For example,
If a customer cancels his/her subscription in the portal, then how we will know about it!!
For it, when customers do any changes in his/her subscription
“customer.subscription.updated” event will be fired and we can listen for this event and, get to know the customer has changed subscription so we need to do appropriate changes in our app also.
Set webhook in your app
In the webhooks.php (in routes folder) file set up a route for handle webhook.
You can use the [Laravel Cashier Package (https://laravel.com/docs/8.x/billing) to handle webhooks.
To set up a webhook for your portal navigate to the “Developers > Webhooks” menu you will find the below screen, here I have added a webhook to handle subscription cancel and update events, it will fire when customers update subscription, and you will receive it.
Click on the “Add endpoint” button and the below pop up will open. In Endpoint URL set the route you have created in the webhooks.php file. Select subscription updated and deleted events.
All done.
For more details, you can use stripe customer portal integration
How to build Pagination with Laravel LivewireLaravel

How to build Pagination with Laravel LivewireLaravel
How to use OneSignal in LaravelLaravel

How to use OneSignal in LaravelLaravel
composer require ladumor/one-signal
php artisan vendor:publish --provider="Ladumor\OneSignal\OneSignalServiceProvider"
Ladumor\OneSignal\OneSignalServiceProvider::class,
'OneSignal' => \Ladumor\OneSignal\OneSignal::class,
ONE_SIGNAL_APP_ID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX ONE_SIGNAL_AUTHORIZE=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X ONE_SIGNAL_AUTH_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

use Ladumor\OneSignal\OneSignal; $fields['include_player_ids'] = ['xxxxxxxx-xxxx-xxx-xxxx-yyyyy'] $message = 'hey!! This is a test push.!' OneSignal::sendPush($fields, $message);
How to use AdminLTE theme with Laravel FortifyLaravel

How to use AdminLTE theme with Laravel FortifyLaravel
Recently, the Laravel team announced a Laravel Fortify. A framework agnostic authentication backend for laravel applications. It provides registration, authentication along with two-factor authentication.
As said above, it is a framework agnostic, so it doesn't provide any blade views with it. You can implement views of your choice of the frontend. Blade, Vue, React with Bootstrap or TailwindCSS, or any other CSS framework.
Today we are going to see how we can use Laravel Fortify with one of the most popular Bootstrap 4 theme AdminLTE v3.
We can actually do that in minutes with the package that we already developed called Laravel UI AdminLTE.
This package also works with the previous laravel version to have an authentication system with Laravel UI for Laravel Frontend Scaffolding.
Let's see step by step, how we can do that.
Install Packages
Install Laravel Fortify and Laravel UI AdminLTE by the following command,
composer require laravel/fortify infyomlabs/laravel-ui-adminlte
Publish Fortify Resources
This command will publish all required actions in the app/Actions
directory along with the Fortify configuration file and migration for two-factor authentication.
php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
Run Migrations
Then run migrations,
php artisan migrate
Add Fortify Service Provider
Next step, add published FortifyServiceProvider to config/app.php
Run AdminLTE Fortify Command
Run the following command,
php artisan ui adminlte-fortify --auth
Install Node Modules and Run a Build
As a next step, install required npm modules and run a build,
npm install && npm run dev
And we are done. Now visit the home page and you should be able to see the full authentication system working including,
- Login
- Registration
- Forgot Password
- Reset Password
- Home page
Laravel AdminLTE UI also provides a starting layout with a sidebar menu and header once you do login. so you are all set to go.
Retrieve count of nested relationship data in LaravelLaravel

Retrieve count of nested relationship data in LaravelLaravel
Recently in one of our client's project, we want to load the count of relation in laravel. But we do not want to retrieve original records.
For example,
We have the following Models,
- Category
- Products
- Orders
For that, we have categories
, products
, orders
, order_items
table. Where in the order_items
table, we got the following fields
- order_id
- product_id
- quantity
So the requirement was, In the Products table, we want to display the total number of orders placed with that item regardless of the quantity in each order. All we need is a number of orders where the product is purchased.
1st way: Query via Relationship
$products = Product::all();
$productsArr = $products->map(function (Product $product) {
$productObj = $product->toArray();
$productObj['orders_count'] = $product->orders()->count();
return $productObj;
});
But the problem with this approach was, we are firing queries to the database for every single product. so if I'm retrieving 100 Products from the database then it will fire 100 additional queries to the database. Imagine if we have thousands of products.
2nd way: Eager Load Relationship and Calculate Count
$products = Product::with('orders')->get();
$productsArr = $products->map(function (Product $product) {
$productObj = $product->toArray();
$productObj['orders_count'] = $product->orders->count();
return $productObj;
});
so this way, we are only firing two queries to the database. But the problem here is, we are loading all the Orders of each product which we don't need at all. so it will consume lots of memory since we are loading lots of orders. so imaging if we retrieve 100 products, and each product has 10 orders, then we are loading 1000 Orders into memory without any need.
3rd way: Use withCount function
The third powerful approach of using withCount
function in Laravel. so we refactored our code like,
$products = Product::withCount('orders')->get();
$productsArr = $products->map(function (Product $product) {
$productObj = $product->toArray();
$productObj['orders_count'] = $product->getAttribute('orders_count');
return $productObj;
});
In this approach, we are firing two queries but no Order models are loaded into memory.
4th Bonus: Using in a nested relationship while multiple eager loading
You can even use it with nested relationships. Imagine a case, where you want to retrieve categories along with its products with orders count.
$categories = Category::with([
'products' => function ($query) {
$query->withCount('orders');
},
'someOtherEagerLoading1',
'someOtherEagerLoading2'
])->get();
$categoriesArr = $categories->map(function (Category $category) {
$categoryObj = $category->toArray();
$categoryObj['products'] = $category->products->map(function (Product $product) {
$productObj = $product->toArray();
$productObj['orders_count'] = $product->getAttribute('orders_count');
return $productObj;
});
return $categoryObj;
});
Hope this will help you to retrieve the count of relationship data without retrieving actual relation data.
Laravel Packages we use everyday at InfyOmLaravel

Laravel Packages we use everyday at InfyOmLaravel
Lots of people ask me frequently, "Which are the laravel packages that you use in almost all projects?" when we meet in Meetup or any other events regardless of its online or physical events.
Let me describe today some of the packages that we almost use in all of the projects.
We are working in Laravel for almost 7+ years and in these years we have used lots of packages, some from the community and some of our own.
I am categorizing these into 2 categories.
- Must used packages
- Common Need/Functionality specific packages
Must used packages
These are the packages which are must be included in all of our projects. No Excuses.
barryvdh/laravel-ide-helper
Laravel exposes a lot of magic methods and properties. IDE Helper is a very good package when it comes to auto-complete those properties and methods. Even it does an amazing job while refactoring properties or methods of the model.
barryvdh/laravel-debugbar
The second one is from the same author, debugbar helps to debug the request in terms of the number of queries fired, time taken by each query, number models retrieved from db, time taken by each request, and much more.
imanghafoori/laravel-microscope
Laravel Microscope improves the readability of your code. Early returns, unnecessary else statements, and many more. so your code looks clean and efficient in terms of execution as well.
beyondcode/laravel-query-detector
One of the problems that we face is, missing eager loading. In ongoing development, sometimes we add relationships objects in the loops, and then laravel fires tons of queries to the database. Laravel Query Detector detects that and gives warning while development environment.
InfyOmLabs/laravel-generator
No application can be ever built without few CRUDs. CRUDs are essential in almost all web applications. Also, APIs of that CRUDs are essentials while building a backend for Mobile or Frontend apps. Laravel Generator is our own developed package that we use in all of the applications to make the CRUD building process faster. It can be used with two themes right now, AdminLTE and CoreUI. But it's also frontend framework agnostic.
Common Need/Functionality specific packages
These are the packages that are used when we particularly need that kind of functionality in the application.
- Single Page application without JS - Livewire
- Role Permissions - spatie/laravel-permission
- Media Management - spatie/laravel-medialibrary
- Full Text Search - Laravel Scout
- Payment - Laravel Cashier
- Frontend Scaffolding - Laravel UI AdminLTE & Laravel UI CoreUI
- APIs token management - Laravel Sanctum
- Realtime Apps - Laravel Echo with Pusher & Laravel Echo Server
- One Signal - Shailesh OneSignal
Will keep this list updating.