Laravel Posts

How to Delete Record using ajax call with Laravel

We work on projects with the admin panel every day. In which we mostly use data tables and we need to delete the record from the data table without page refresh.

So, today I will show you how to extract a record using Ajax. It's very easy to integrate.

Let's take one example. I have a Category data table and I want to delete one category from the table without refreshing the page. Now, what am I doing for that? First of all, I add a class for the listen to a click event into the delete button and it says delete-btn.

See the following image for where I added a class.

delete-record-using-ajax-in-laravel/1

I used SweetAlert for the confirmation popup. let add sweet alert's CSN into the index.blade.php.

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

Let's declare routes of the delete record.

<script>let categoryUrl = '{{route('categories.index')}}'; </script>

Next steps, I'm going to listen to the click event of the delete button. one more thing does not forget to add the record id into the data attribute to the delete button. see the above image for it. I highlighted it with a yellow line.

So the general practices we use in Laravel is to write the following code to listen to a click event and delete a record,

$(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,                             
              })                     
            }             
        });                 
    });         
});

Now we are done with the front-end side and need to look into it backend side.

Let's declare the destroy method into the category Controller. I hope are you generating crud with InfyOm Laravel Generator. so, the Destroy method and routes are there. If not please create a route. if the destroy method is there then need to change the response of that method.

The destroy method code looks like,

 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.');
    }
August 19, 20203 minutesShailesh LadumorShailesh Ladumor
Setup Laravel Livewire with Basic Component Example

Laravel Livewire is used to build dynamic web pages that work without ajax or any javascript code. We can build dynamic components with livewire with less code and more functionalities.

I hope this basic introduction will be enough to start laravel livewire.

Now let's move to the installation steps, and I hope you already have set up your laravel project.

Install Livewire

 composer require livewire/livewire 

Include the javascript and styles (On your master blade file)

  ...      
@livewireStyles   

   ...
     @livewireScripts

Create Your Component

Here we are going to create a component to create a summation of 2 values without hitting any buttons, it will do a summation of 2 values as you type in text boxes.

Now let's create our component by hitting the following command :

php artisan make:livewire Summation

it will create 2 files as shown below:

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

Include the component

Include the created component to your view where you want to show.

    ...
    @livewireStyles

    ...

    @livewireScripts

Now let's first do a change in our livewire component Summation.php

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');
   }
 }

Here we have to take 2 public properties value1, value2, and sum. and in the mounting method (which will be called when the page is loaded the first time) I have replaced the sum property value to 0.

And In the render method, I have done a summation of the 2 public property values. which will be directly accessed values of input from blade files directly here. but how ?? we will see soon.

Now let's change the livewire blade component.

  

Here we have bound all properties by using wire:model. so as we will type in input box 1 it will be directly accessed by $value1 into the component.

and the property $sum will be changed as we change the input box values.

So that's how cool livewire is. you can create different dynamic components as you need by using livewire.

Stay tuned to read more interesting posts on livewire.

August 07, 20202 minutesVishal RibdiyaVishal Ribdiya
How to Integrate the Stripe Customer Portal

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

setting

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.

product

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.

portal settings

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

api keys

  • 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([undefined]);
  • 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" 
}

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

webhook

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.

webhook endpoint

All done.

For more details, you can use stripe customer portal integration

July 25, 20203 minutesMonika VaghasiyaMonika Vaghasiya
How to build Pagination with Laravel Livewire

Livewire is a very awesome thing that I have ever seen, the old school developers are still using the jquery and ajax concept to not refresh the page. But forget the jquery and ajax stuff. If you are good at PHP then you can do the same with Laravel Livewire.

Wait what?

Load dynamic data on the page without using ajax? Yes, it is possible with Laravel Livewire. So that is all about laravel livewire, and in this tutorial, we will see how to build laravel pagination with laravel livewire.

Let's start and I hope you have already set up the livewire. Let's say you already have created a component named UsersListing Now in the users listing, we want to paginate all users and we will list 10 records per page.

How to use pagination with Laravel Livewire

Livewire provides a trait called WithPagination and you have to add it into your component UsersListing. Check out the following code:

use Livewire\WithPagination; 
use Livewire\Component; 
class UsersListing extends Component 
{ 
   use WithPagination;

   public function render() 
     { 
       return view('livewire.users.index', [ 'users' => User::paginate(10), ]); 
     } 
} 

And to load pagination you have to add the following code:

@foreach ($users as $user) ... 

@endforeach {{ $users->links() }} 

That's it, and your laravel pagination now works like charm without page refresh. There is much more about pagination like how to use it with a custom view, how to use it with a custom theme. We will see it in our next tutorial, until then enjoy the code

July 11, 20201 minuteVishal RibdiyaVishal Ribdiya
How to use One Signal in Laravel

The OneSingnal is the market leader in push notification providers. It provides mobile + web push, email & in-app messages, and an easy way to send notifications. OneSignal provides official core PHP APIs but not the Laravel package. We are using OneSignal in many projects and write a bunch of line code in all projects where we needed OneSingnal.

One day I had an idea in my mind why I should not write a Laravel wrapper for OneSignal?. Finally, I wrote the shailesh-ladumor/one-signal Laravel Wrapper for it. Using this package, we can write neat & clean code and just a few lines of code.

OneSignal add this package in his official docs here

You can watch the following video tutorial or follow the article.

This package also works with the previous Laravel version.

Today we are going to see how we can use Laravel OneSignal Wrapper in Laravel. Let's see step by step, how we can do that.

Spet 1: Install Packages

Install shailesh-ladumor/one-signal by the following command,

composer require ladumor/one-signal

Step 2: Publish the config file

Run the following command to publish config file,

php artisan vendor:publish --provider="Ladumor\OneSignal\OneSignalServiceProvider"

Step 3: Add Provider

Add the provider to your config/app.php into the provider section if using a lower version of Laravel,

Ladumor\OneSignal\OneSignalServiceProvider::class

Step 4: Add Facade

Add the Facade to your config/app.php into aliases section,

'OneSignal' => \Ladumor\OneSignal\OneSignal::class

Configure a .env file with following keys

ONE_SIGNAL_APP_ID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX 
ONE_SIGNAL_AUTHORIZE=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X 
ONE_SIGNAL_AUTH_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

ONE_SIGNAL_AUTH_KEY is optional if you do not want to create an app. I hope you are familiar with the One Signal Platform and know how to get APP_ID and AUTHORIZE. If not, you should see the below image for how to get it.

onesignal-in-laravel/1

So, we are done. Let's check how to send push notifications.

Check out this code to send a push notification.

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

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 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 login. so you are all set to go.

June 27, 20202 minutesMitul GolakiyaMitul Golakiya
Retrieve count of nested relationship data in Laravel

Recently in one of our client's projects, 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,

  1. Category
  2. Products
  3. 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.

September 18, 20202 minutesMitul GolakiyaMitul Golakiya
Laravel Packages we use everyday at InfyOm

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

  1. Most used packages
  2. Common Need/Functionality specific packages

Most used packages

These are the packages which 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 a warning while developing the environment.

InfyOmLabs/laravel-generator

No application can be ever built without a few CRUDs. CRUDs are essential in almost all web applications. Also, APIs of CRUDs are essential 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.

Will keep this list updating.

September 11, 20202 minutesMitul GolakiyaMitul Golakiya