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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

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 *