Laravel 10 withCount() with Where Condition Example
Hello Artisan, today I'll show you how to use Laravel withCount() with Where Condition. In this brief tutorial, we'll demonstrate a swift and uncomplicated approach to utilizing Laravel's withCount along with conditions. We'll delve into the topic of employing withCount alongside specific conditions in Laravel. The following guide presents a simple, step-by-step explanation of how to employ withCount within Laravel's Eloquent relationships.
We'll provide a straightforward example to illustrate the usage of withCount within Laravel's Eloquent relationships. Furthermore, we'll showcase an instance of utilizing withCount in conjunction with a where condition. Throughout this tutorial, we'll establish a connection between the Category and Product entities to highlight how to set up relationships and retrieve relevant information. This method of using withCount is applicable across various Laravel versions, including 6, 7, 8, 9, and 10.
Creating the Category and Product Model, you can proceed by executing the following command
php artisan make:Model Category -m
php artisan make:Model Product -m
Let's see example with output:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = [
'name', 'is_active'
];
public function products()
{
return $this->hasMany(Product::class);
}
}
<div class="filename">app\Models\Product.php</div>
<?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', 'is_active'
];
}
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function index()
{
$categories = Category::select("id", "name")
->withCount('products')
->get()
->toArray();
dd($categories);
}
}
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function index()
{
$categories = Category::select("id", "name")
->withCount([
'products as active_products_count' => function ($query) {
$query->where('is_active', '1');
},
])
->get()
->toArray();
dd($categories);
}
}
That's it for today. I hope it'll be helpful in upcoming project. You can also download this source code from GitHub. Thanks for reading. ๐