Laravel Eloquent withSum() withCount() Example Tutorial

Laravel Eloquent withSum() withCount() Example Tutorial

Laravel eloquent query withSum and withCount of related table. In this example, you will learn eloquent withcount and withsum().

Now, this tutorial will show you example of how to use withSum() and withCount() with laravel relationship eloquent using Category and Product table.

As well as, you can use withSum() and withCount() with laravel 6, laravel 7 and laravel 8 version.

Laravel Eloquent withsum and withcount with relationships tutorial

Category Model:

First of all, create category model and add the following code into it:

<?php

  

namespace App\Models;

  

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

  

class Category extends Model

{

    use HasFactory;

  

    /**

     * Get the comments for the blog post.

     */

    public function products()

    {

        return $this->hasMany(Product::class);

    }

}

Product Model:

Now, create product model and add the following code into it:

<?php

  

namespace App\Models;

 

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

  

class Product extends Model

{

    use HasFactory;

  

    protected $fillable = [

        'name', 'price'

    ];

}

Laravel relationship with withSum() Example:

You can use withSum() eloquent in laravel as follow:

<?php

  

namespace App\Http\Controllers;

  

use App\Models\Category;

  

class MyController extends Controller

{

    /**

     * Write code on Method

     *

     * @return response()

     */

    public function index()

    {

        $categories = Category::select("id", "name")

                        ->withSum('products', 'price')

                        ->get()

                        ->toArray();

 

        dd($categories);

    }

}

Result:

Array

(

    [0] => Array

        (

            [id] => 1

            [name] => Mobile

            [products_sum_price] => 330

        )

    [1] => Array

        (

            [id] => 2

            [name] => Laptop

            [products_sum_price] => 410

        )

)

Laravel relationship with withCount() Example:

You can use withCount() eloquent in laravel as follow:

<?php

  

namespace App\Http\Controllers;

  

use App\Models\Category;

  

class MyController extends Controller

{

    /**

     * Write code on Method

     *

     * @return response()

     */

    public function index()

    {

        $categories = Category::select("id", "name")

                        ->withCount('products')

                        ->get()

                        ->toArray();

 

        dd($categories);

    }

}

Result:

Array

(

    [0] => Array

        (

            [id] => 1

            [name] => Mobile

            [products_count] => 3

        )

    [1] => Array

        (

            [id] => 2

            [name] => Laptop

            [products_count] => 2

        )

)

Recommended Laravel Tutorials

Recommended:- Laravel Try Catch

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

One reply to Laravel Eloquent withSum() withCount() Example Tutorial

  1. Thanks for sharing information. keep sharing

Leave a Reply

Your email address will not be published. Required fields are marked *