@sajidulislam0 in your category model you need a hasmany relationship to post.
then all you need now is:
Category::orderBy('name', 'asc')->withCount('posts')->paginate(10)
https://laravel.com/docs/10.x/eloquent-relationships#one-to-many
Hi all,
I have made a category and a posts table. On post table I'm storing the category id's in the JSON format on posts table. Now, I would like to get total count of posts for each category where categories are store on a different table. I've tried everything I could but as a beginner I'm still on loss. So, I would like to know what is the proper/efficient way to do this?
This is my Category Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model{
use HasFactory;
protected $table= 'categories';
// Get assigned parent category to it's child category
public function getChildCategory(){
return $this->hasMany(SubCategory::class,'parent_cat_id','id');
}
// Get Attached Category thumbnail by ID
public function getCategoryThumbID(){
return $this->hasOne(Media::class, 'id', 'image_id');
}
}
This is my posts model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Posts extends Model{
use HasFactory;
protected $table= 'posts';
// Get Attached Post thumbnail by ID
public function getPostsThumbID(){
return $this->hasOne(Media::class, 'id', 'post_thumbnail');
}
public function categories(){
return $this->belongsToMany(Category::class, 'id');
}
}
This is the category controller
`<?php
// Get Total count of post based on the category
namespace App\Http\Controllers;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\Models\Category;
use App\Models\Media;
use App\Models\Posts;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class CategoryController extends Controller{
function allView(){
if (View::exists('backend.category.all')) {
$data=[
'title' => 'List of category',
'items' => Category::orderBy('name', 'asc')->paginate(10),
'categoryImage' => Media::all(),
// 'categoryCount' => $postCount,
'mode' => 'add',
];
return view('backend.category.all',compact('data'));
}
}
function save(Request $request){
// Validate the request...
$this->validate($request, [
'Category_Name' => ['required','unique:App\Models\Category,name'],
'category_image' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
]);
$cat = new Category;
$cat->name = $request->Category_Name;
$cat->status = $request->status;
// Category image upload
$this->categoryImageUpload($request,$cat);
// Save the query
$query = $cat->save();
if($query){
return back()->with('success', 'Entry added successfully');
}
}
function edit($id){
if (View::exists('backend.category.all')) {
$data=[
'title' => 'Edit category Info',
'editItems' => Category::findOrFail($id),
'items' => Category::orderBy('name', 'asc')->paginate(10),
'mode' => 'edit'
];
return view('backend.category.all',compact('data'));
}
}
function update(Request $r){
$editcat = Category::find($r->update_id);
// Validate the request...
$this->validate($r, [
'Category_Name' => ["required","unique:App\Models\Category,name,$r->update_id"],
'category_image' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
]);
$editcat->name = $r->Category_Name;
$editcat->status = $r->status;
// Category image Update
$this->categoryImageUpload($r,$editcat);
$query= $editcat->save();
if($query){
return redirect(Route('category.all'))->with('success','Entry Updated Successfully');
}else{
return redirect(Route('category.all'))->with('error','Something went wrong');
}
}
function destroy($id){
$itemId = Category::findOrFail($id);
$successDelete= $itemId->delete();
if( $successDelete){
return redirect()->route('category.all')->with('success', 'Entry deleted successfully');
}
}
private function categoryImageUpload($request,$categryInstance){
$directory = 'category';
if (!file_exists(public_path($directory))) {
mkdir(public_path($directory), 0777, true);
}
if (!File::isWritable(public_path($directory))) {
return back()->withErrors(['message' => 'The uploads directory is not writable']);
}
if ($request->file('category_image')!=null){
$media = new Media;
// Get the uploaded file from the request
$image = $request->file('category_image');
// Get the original name of the image
$originalName = $image->getClientOriginalName();
$fileName = time().'_'.$originalName;
// Move the uploaded file to the desired location
$destinationPath = public_path($directory);
$image->move($destinationPath, $fileName);
$media->image_name = $fileName;
$media->image_path = $directory.'/'.$fileName;
$media->save();
$categryInstance->image_id=$media->id;
}else{
$media = new Media;
$categryInstance->image_id=NUll;
}
}
}`
Any help would be much appreciated
Please or to participate in this conversation.