Laravel Eloquent withCount() and withSum() Example

Laravel withCount and sumSum eloquent example; Through this tutorial, i am going to show you how to use withSum and withCount eloquent with relationship in laravel apps.

Let’s create category and product models and create relationship between these models; is as follows:

Create eloquent relationship in category model; as follows:

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

Then create product model and add the following code into it; is as follows:

<?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 withSum() with Relationship Example

Let’s take example using withsum() with relationship eloquent in laravel apps; is as follows:

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

Laravel withCount() with Relationship Example

Let’s take example using withCount() with relationship eloquent in laravel apps; is as follows:

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

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.