Laravel 5.7 Comment count for different posts - php

I am stucked at point where i got comment count for posts but it shows count of all comments of all posts on every post. I would like to know how to output in blade comment count for post ID
here is controller:
$posts = $posts->orderBy("posted_at", "desc")
->paginate(config("blogetc.per_page", 10));
$comments = BlogEtcComment::all();
return view("blogetc::index", [
'posts' => $posts,
'title' => $title,
'comments' => $comments,
]);
blade:
#foreach($posts as $post)
<section class="blog_area p_120">
<div class="container">
<div class="row">
<div class="col-lg-8">
<div class="blog_left_sidebar">
<article class="blog_style1">
<div class="blog_img">
<img class="img-fluid" src="blog_images/{{$post->image_large}}" alt="">
</div>
<div class="blog_text">
<div class="blog_text_inner">
<div class="cat">
<a class="cat_btn" href="{{$post->url()}}">{{$post->slug}}</a>
<i class="fa fa-calendar" aria-hidden="true"></i>{{$post->created_at}}
<i class="fa fa-comments-o" aria-hidden="true"></i> {{count($comments)}}
</div>
<h4>{{$post->title}}</h4>
<p>{!! $post->generate_introduction(400) !!}</p>
<a class="blog_btn" href="{{$post->url()}}">Lasīt vairāk</a>
</div>
</div>
</article>
</div>
</div>
</div>
</div>
</section>
#endforeach

//Quickfix:
//assuming your posts table is called posts and that in your blogetccomments table //you have a post_id column pointing to the original post. Try something like
$posts = DB::table('posts')
->leftJoin('blogetccomments', 'posts.id', '=', 'blogetccomments.post_id')
->selectRaw('posts.*, count(blogetccomments.post_id) as commentcount')
->groupBy('posts.id')
->get();
In your blade template, Access the comments count for each post, as follows..
#foreach($posts as $post)
...
{{$post->title}}...
{{$post->commentcount}}
...
#endforeach

You can use withCount() to get count of comments for a specific post :
$posts = $posts->withCount('comments')
->orderBy("posted_at", "desc")
->paginate(config("blogetc.per_page", 10));
Above would require you to have comments relation on your Post Model :
Post Model :
public function comments()
{
return $this->hasMany(BlogEtcComment::class);
}
BlogEtcComment Model :
public function post()
{
return $this->belongsTo(Post::class);
}
And then in blade :
#foreach($posts as $post)
<p>Post : $post->id</p>
<p>Comments : $post->comments_count</p>
#endforeach

Related

How to show summary data in Laravel Blade inside of ForEach Loop?

I am trying to display a ForEach loop on my view that shows each code type. That part works. I am having trouble figuring out how to display a count of how many pieces of code (stored in another table) exist for each code type. I don't understand how to use the id of the code_type to query the code_type_selected table and to return that count.
In my CodeType model
protected $fillable = [
'name',
'color',
'icon'
];
public function codeTypesSelected() {
return $this->hasMany(CodeTypesSelected::class, 'code_type_id', 'id');
}
In my CodeTypeSelected model
protected $fillable = [
'code_type_id',
'code_id',
];
public function codeTypes() {
return $this->belongsTo(CodeType::class, 'id', 'code_type_id');
}
In my controller
public function index(Request $request)
{
$codeTypes = CodeType::latest()->get();
$codeTypesSelected = CodeTypesSelected::latest()->get()->groupBy('code_type_id');
//dd($codeTypesSelected);
return view('code_layout.index', compact('codeTypes', 'codeTypesSelected'));
}
And in my view
<!-- /. ROW -->
<div class="row">
#foreach($codeTypes as $codeTypeItem)
<div class="col-md-3 col-sm-12 col-xs-12">
<div class="panel panel-primary text-center no-boder bg-color-{{ $codeTypeItem->color }}">
<div class="panel-left pull-left {{ $codeTypeItem->color }}">
<i class="fa fa-{{ $codeTypeItem->icon }} fa-5x"></i>
</div>
<div class="panel-right">
<h3>
{{ count($codeTypesSelected) }}
</h3>
<strong> {{ $codeTypeItem->name }} </strong>
</div>
</div>
</div>
#endforeach
</div>
<!-- /. ROW -->
Have you tried this
CodeType::latest()->withCount('codeTypesSelected')->get()

Laravel Collection get one of values by key

I'm new to Laravel and I'm trying to get one of the values in one collection by one ID retrieved from another collection.
My function returns 2 Collections:
public function index()
{
$category = BlogCategory::all(['id', 'name']);
$post = BlogPost::orderBy('id', 'desc')->take(14)->get();
return view('blog.index', ['posts' => $post], ['categories' => $category]);
}
In a foreach loop I'm getting values from collections:
#foreach($posts as $post)
#if($loop->iteration > 2)
<div class="col-sm-6 col-md-3 d-flex justify-content-center other-post">
<a href="#">
<img src="#" alt="">
<p class="post-category">{{ $categories->get($post->category_id) }}</p>
<h5 class="post-title">{{ $post->title }}</h5>
</a>
</div>
#endif
#endforeach
I'm partially getting the result as you can see in the image below, but I want to get only the name.
Here is the code that I'm trying to figure out
{{ $categories->get($post->category_id) }}
If there is a better or correct way to do it, let me know.
Blog Posts migration:
public function up()
{
Schema::create('blog_posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->longText('content');
$table->mediumText('slug');
$table->bigInteger('author_id')->unsigned();
$table->bigInteger('category_id')->unsigned();
$table->timestamps();
$table->foreign('author_id')->references('id')->on('blog_authors');
$table->foreign('category_id')->references('id')->on('blog_categories');
});
}
You should put in place the relationships between BlogPost and BlogCategory models, seen that you already have a category_id field in BlogPost model, i.e.:
in BlogPost Model:
public function category(){
return $this->belongsTo(\App\BlogCategory::class);
}
in BlogCategory Model:
public function posts(){
return $this->hasMany(\App\BlogPost::class);
}
Next you can eager load categories with the $posts in your controller with only two queries:
public function index()
{
$posts = BlogPost::with('category')->orderBy('id', 'desc')->take(14)->get();
return view('blog.index', compact('posts'));
}
Then in your view you can access each $post->category object directly because eager loaded in the controller:
#foreach($posts as $post)
#if($loop->iteration > 2)
<div class="col-sm-6 col-md-3 d-flex justify-content-center other-post">
<a href="#">
<img src="#" alt="">
<p class="post-category">{{ $post->category->name }}</p>
<h5 class="post-title">{{ $post->title }}</h5>
</a>
</div>
#endif
#endforeach
It could be optimized, first, you need to make relation one to many from categories to posts
first: make sure that you have in posts migrations category_id column
Second: Open Category Model and write this method this will allow you to fetch posts that belong to the category
public function posts(){
return $this->hasMany(\App\Post::class);
}
Third: open shop model and write this method this will allow you to fetch category that belongs to the post
public function catgeory(){
return $this->belongsTo(\App\Category::class);
}
Finally: you will edit your view like this one
#foreach($posts as $post)
<div class="col-sm-6 col-md-3 d-flex justify-content-center other-post">
<a href="#">
<img src="#" alt="">
<p class="post-category">{{ $post->category->title }}</p>
<h5 class="post-title">{{ $post->title }}</h5>
</a>
</div>
#endforeach
and of course, you wouldn't call categories in your controller anymore
public function index()
{
$post = BlogPost::orderBy('id', 'desc')->take(14)
->with('category')->get();
return view('blog.index', ['posts' => $post]);
}
Maybe it better use a relation to drive this situation. You can load in the controller the data in this way.
In the Model Post:
function categories(){
return $this->belongsToMany('App\BlogCategory')->select(array('id', 'name');
}
Maybe is hasOne -> the relationship if you don't have a table pivot...
In the Controller:
public function index()
{
$data['posts'] = BlogPost::orderBy('id', 'desc')->take(14)->with('categories')->get();
return view('blog.index', $data);
}
In the View:
#foreach($posts as $post)
#if($loop->iteration > 2)
<div class="col-sm-6 col-md-3 d-flex justify-content-center other-post">
<a href="#">
<img src="#" alt="">
<p class="post-category">{{ $post->categories->name }}</p>
<h5 class="post-title">{{ $post->title }}</h5>
</a>
</div>
#endif
#endforeach
this line $categories->get($post->category_id) return for you an array of category, so the solution for you here is just like bellow:
{{ $categories->get($post->category_id)['name'] }}

Display posts belonging to category in laravel

I am trying to get the posts that belong to each category, i had this working before but i can't seem to find what i have done wrong here.
I have a Post Table and a Categories Table
ROUTE
Route::get('articles/category/{id}', ['as' => 'post.category', 'uses' => 'ArticlesController#getPostCategory']);
CONTROLLER
public function getPostCategory($id)
{
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
$categories = PostCategory::all();
// return view
return view('categories.categoriesposts')->with('postCategories', $postCategories)->with('categories', $categories);
}
VIEW
#foreach($postCategories->posts as $post)
<div class="well">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placekitten.com/150/150">
</a>
<div class="media-body">
<h4 class="media-heading">{{ substr($post->title, 0, 50) }}</h4>
<p class="text-right">By Francisco</p>
<p>{{ substr($post->body, 0, 90) }}</p>
<ul class="list-inline list-unstyled">
</ul>
</div>
</div>
</div>
#endforeach
POST MODAL
public function postCategory()
{
return $this->belongsTo('App\PostCategory');
}
POSTCATEGORY MODAL
class PostCategory extends Model
{
// connect Categories to Posts tables
protected $table = 'post_categories';
// Category belongs to more than 1 post
public function posts()
{
return $this->hasMany('App\Post', 'post_category_id');
}
}
I can't see what i am doing wrong every time I go to a category it shows
Trying to get property of non-object
Any help will be much appreciated thanks
replace your lines:
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
with:
$postCategories = PostCategory::find($id)->posts;
Change your line in your PostCategoryModel to:
return $this->hasMany('App\Post', 'post_category_id','post_category_id');

Laravel compact is not working

I'm trying to make a posting system, with a resource routing combination on the posts. When I try to run the app to view the posts, it returns an error stating that the posts could not be found within the view. I have the controller code for the index and the show functions:
public function index()
{
$posts = Post::latest()->get();
return view('view', compact('posts'));
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
The view that I have for the app uses the post variable to display the posts:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-2">
<div class="panel panel-default">
<!-- Posts will be displayed on the same panel -->
<div class="panel-body" id="view">
#foreach($posts as $post)
<article id="post">
<a href="/view/posts{{ $post->id }}">
{{ $post->title }}
</a>
<div class="body">
{{ $post->body }}
</div>
<!-- Footer for posts will include interaction features -->
</article>
#endforeach
</div>
</div>
</div>
</div>
</div>
Is there something that the laravel installation isn't doing correctly? Is the compact function set up correctly?
Your controller index function should be something like this:
public function index()
{
$posts = Post::get();
return view('posts.index', compact('posts'));
}
The return of the index action is wrong
return view('view', compact('posts'));
Change 'view' with 'posts'
Use compact('posts')
If you're a beginner checkout the laracasts video series to get a good understanding of the Laravel framework.

Laravel get profile name

I'm laravel newbie and I'm making simple CMS. So i have simple question:
I wan't when click on avatar - redirect to user profile (http://example.com/profiles/nickname/id)
In DB it saves that:
as you see author_id I have, now I need to get author name from users table:
And then generate url: http://example.com/profiles/Evaldas/2 (Evaldas, because author_id is 2 in topics table)
My routes file:
Route::get('topic/{tname}/{tid}', 'viewTopic#showTopic');
My viewTopic.php Controller:
<?php
namespace App\Http\Controllers;
use DB;
use View;
class viewTopic extends Controller
{
public function showTopic($tname, $tid)
{
return View::make('posts', [
'topics' => DB::table('topics')
->where('id', $tid)
->where('seo_title', $tname)
->first(),
'posts' => DB::table('posts')
->where('topic_id', $tid)
->select()
->get()
]);
}
}
And layout:
#extends('layouts.main')
#section('content')
<div class="media">
<div class="media-left">
<a href="HERE MUST BE HREF TO PROFILE">
<img class="media-object" src="http://localhost/uploads/avatars/2.jpg" style="width: 64px">
</a>
</div>
<div class="media-body" rel="#author{{ $topics->author_id }}">
<h4 class="media-heading">{{ $topics->title }}</h4>
#if(!empty($topics->text))
{{ $topics->text }}
#else
Message empty :(
#endif
</div>
#foreach($posts as $post)
<div class="media">
<div class="media-left">
<a href="HERE MUST BE HREF TO PROFILE">
<img class="media-object" src="http://localhost/uploads/avatars/1.png" style="width: 64px">
</a>
</div>
<div class="media-body" rel="#post{{ $post->pid }}">
{{ $post->text }}
</div>
</div>
#endforeach
</div>
#stop
Thanks so much in advance :)
If you want to use the Query Builder, you can use the join() method:
DB::table('posts')
->where('topic_id', $tid)
->join('users', 'user.id', '=', 'posts.author_id')
->select()
->get()
This way, the user information will be available:
$post->nickname
You can then build your URL using a laravel helper, for exemple, if you have a profile route:
<a href="{{route('profile', ['nickname' => $post->nickname, 'id' => $post->author_id]);}}">
An other method is to create models for your tables and define relationship between them.
See this: http://laravel.com/docs/5.1/eloquent-relationships
Using this method, you will be able to write things like $post->author->nickname

Categories