Laravel Eloquent withSum() and withCount() 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 very easy 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <?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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <?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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <?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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | Array ( [0] => Array ( [id] => 1 [name] => Mobile [products_count] => 3 ) [1] => Array ( [id] => 2 [name] => Laptop [products_count] => 2 ) ) |