I´m traying to create one counter for my blog´s categories. This should appear to the right name side of my category . i´m using my model with variable appends, that after i will use in my blade for show my result in one span. But i don´t know very well how i can use count in my Model. I´m doing this in my model Blog.
my variable appends contain:
protected $appends = [
'custom_fields',
'has_media',
'restaurant',
'blog_category',
'viewer',
'postCounter',
];
i´m traying this:
return $this->blogs()->count();
i have a relation between blog and blog_category with:
public function blogCategory()
{
return $this->belongsTo(\App\Models\BlogCategory::class, 'blog_category_id', 'id');
}
i want to do in my view appear for example:
innovation (2)
in my view i´m doing this:
#foreach($categories as $category)
<li>{{ trans('web.blog_category_'.$category->name) }}<span>{{$category->postCounter}}</span></li>
#endforeach
but always returned me 0, and i have post with categories
updated
With laravel relationship withCount you can do this easily. If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.
add withCount method to your query
$categories = Category::withCount('blogCategory')->get();
You can access the count in your foreach loop
// $category->blogCategory_count
#foreach($categories as $category)
<li>
<a href="{{ url('blogs/'.$category->name) }}">
{{trans('web.blog_category_'.$category->name) }}
</a>
<span>{{$category->blogCategory_count}}</span>
</li>
#endforeach
Related
I have a Laravel app and a model Category. It has a relation to itself called parent
Category.php
public function parent(): BelongsTo
{
return $this->belongsTo(self::class, 'parent_uuid', 'uuid');
}
I'm trying to make this kind of URL,
ex.: domain.com/mobile-phones/smartphones
('mobile-phones' - category's parent, 'smartphones' - category itself)
In the routes file it should be:
Route::get('/{parent}/{category}', ...)->name('category');
Is there a way to code so i use just one Route Parameter?
For example:
Route::get('/{category:parent}/{category}', ...)->name('category');
Also a way so that in blade files when i generate the url to use just the category.
route('category', ['parent' => $category->parent, 'category' => $category]); // No
route('category', $category); // Yes
I have tried making the route binding as follows:
/{category:parent}/{category}
But it gives the error that the parameter category can be used just once.
I would define the route like this
Route::get('/categories/{parent}/{category}')->name('category');
Because it is easy to read
and on blade run a loop on the devices and just prepare the anchor tag for the route.
#foreach ($smartPhone as $phones)
<a href="/categories/{{ $smartPhone->parent->name }}/{{ $smartPhone->categories }}">
Categories
</a>
#endforeach
or if wanna display the category names
#foreach ($smartPhone as $phones)
<a href="/categories/{{ $smartPhone->parent->name }}/{{ $smartPhone->categories }}">
{{ $smartPhone->category }}
</a>
#endforeach
I use Bagisto E-Commerce platform (build laravel + vue) and I have created package where I want list categories and filter products by category name.
I don't know how exactly filter products by one view and in bagisto they list products by category page e.g. example.com/category-name
I try to use this example, but can't get it working, because I don't know where I get class "Products" and function AllProducts.
Can someone guide me in the right direction of how I could get this to work correctly?
This is what I'm trying to do: https://codepen.io/mrsingleton/pen/aYVBvV
My code in products view:
$categories = [];
foreach (app('Webkul\Category\Repositories\CategoryRepository')->getVisibleCategoryTree(core()->getCurrentChannel()->root_category_id) as $category) {
array_push($categories, $category);
}
?>
#if (count($categories))
<div class="list-container" style="text-align:center;margin-top: 50px;">
<ul class="list-group">
#foreach ($categories as $key => $category)
<li> {{ $category->name }} </li>
#endforeach
</ul>
</div>
#endif
In Bagisto, Laravel translatable has been used. Thats why you need to use the different approaach to achieve this. As directly by name, you won't be able to achive because the rest columns are on different tables i.e. category_translations.
If you check the Categories model in namespace i.e. Webkul\Category\Models\Category, it is already linked to the Product model. So you can directly chain it to fetch all associated products.
/* fetch category by name */
$categoryName = 'Category 1';
$category = Category::whereHas(
'translations',
function ($query) use ($categoryName) {
$query->where('name', $categoryName);
}
)->first();
$relatedProducts = $category->products;
/* rest is your operations */
firstly, i'm a newbie in laravel.
i insert a array data as a string in server.
column name "category_id" & value like "1,2,3,4".
Now i just want to show these id's category name with eloquent relationship.
Using laravel latest version.
view page
{{$category_var = explode(',',$post->category_id)}}
#foreach($category_var as $category)
#if($category)
<span class="badge mb-3">{{$post->category->category}} </span>
#endif
#endforeach
class page
public function category(){
return $this-> belongsTo(Category::class);
}
Controller page
public function index()
{
$posts = post::paginate(9);
return view('pages/home',compact('posts'));
}
anything else need just ask me.
Thanks
just use the benefits of models and relation like below:
#foreach($posts as $post)
#foreach($post->category as $category)
<span class="badge mb-3">
{{ $category->(what ever you want from category model) }}
</span>
#endforeach
#endforeach
I have set up two model with its row in table. And made a single form to fill both tables and it works perfectly
Tour.php
public function featuredImage()
{
return $this->hasOne('App\FeaturedImage');
}
tours table
id|name|content|featured_status
featuredImage.php
public function tour()
{
return $this->belongsTo('App\Tour');
}
Featured_images table
id|tour_id|path|name
Code in my controller to pass data to view.
$tours = Tour::where('featured', 1)->get();
return view('public.pages.index')
->withTours($tours);
Code in my view
#foreach($tours as $featured)
<div class="thumbnail">
<img src="{{$featured->featuredimage->path}}" alt="{{$featured->featuredImage->name}}">
</div>
<h4>{{$featured-name}}</h4>
#endforeach
The trouble is I'm not able to fetch featured images by writing
{{$featured->featuredimage->path}}
and the error is
Trying to get property of non-object
on the line {{$featured->featuredimage->path}}. I have used this method in my previous project and it had worked perfectly but it isn't going well in this one.
I tried replacing {{$featured->featuredimage->path}} with {{$featured->featuredImage->path}} but didn't worrked out.
Do this:
{{ $featured->featuredImage()->path }}
Also, you're creating a lot of additional queries here. You should use eager loading to solve N + 1 problem:
$tours = Tour::with('featuredImage')->where('featured', 1)->get();
And display data with:
{{ $featured->featuredImage->path }}
I was wondering what the cleanest way was to count the number of posts that are connected to a category in my blog.
Here is how the table relationship is set up.
What I have is a hasMany relationship from the Category to the Post models like this:
In Categories Model
public function blog_posts()
{
return $this->hasMany('App\Http\Models\Blog_Post', 'category_id');
}
And in the Blog_Post Model
public function blog_categories()
{
return $this->belongsTo('App\Http\Models\BlogCategories', 'category_id');
}
In effect all I want to do is be able to return to my view the total number of posts that each category has as shown below. Where x is the number of posts within each category.
cat1 (x)
cat2 (x)
cat3 (x)
It's not hard to count I know however as I only want a count I do not want to also retrieve the records as they are not required and I also do not want to create more queries than is necessary.
I have not completed the view as yet but probably a start would be to pass through the categories in a loop to display each and add the count at the same time?
#foreach ($categories as $category)
{!! $category->name !!} - {!! Count of posts here !!}
#endforeach
Hopefully that is clear(ish)!
Eager load the relation in your controller:
public function index()
{
$categories = Category::with('blog_posts')->get();
return view('categories.index', compact('categories'));
}
You can then use the count() method on the blog_posts relation when looping over categories in your view:
#foreach ($categories as $category)
<li>{{ $category->name }} ({{ $category->blog_posts->count() }})</li>
#endforeach
EDIT: Since Laravel 5.3, you can use withCount() to load counts of relations, i.e.
$categories = Category::withCount('blog_posts')->get();
This will make the count available via a property:
foreach ($categories as $category) {
$blog_posts_count = $category->blog_posts_count;
}
The nicest way to do it with eager loading support I know is to create a separate relation with the post count. Check this out:
public function blog_posts_count() {
return $this->hasOne('App\Http\Models\Blog_Post', 'category_id')
->selectRaw('category_id, count(*) as aggregate')
->groupBy('category_id');
}
public function getBlogPostsCountAttribute() {
if(!array_key_exists('blog_posts_count', $this->relations))
$this->load('blog_posts_count');
$related = $this->getRelation('blog_posts_count');
return $related ? (int) $related->aggregate : 0;
}
Usage is simple:
{{ $category->blog_posts_count }}