So yesterday I success to count comment from post, now I want to show comment in admin dashboard, so here is my code in controller
public function getComment()
{
$user = Auth::user();
$posts = $user->posts();
foreach ($posts as $key => $value) {
$posts[$key]->post_comments = PostComment::where('post_id', $value->id)->get();
}
return $posts;
}
and here is my web.php route code to get this comment
Route::get('/comment/post/{id}', 'DashboardController#getComment');
But it retrieve all comment even in different post, I only want to get comment from same post that I want. The weird one is when I click the button it retrieve random id not the id from the post, it look like this
http://127.0.0.1:8000/comment/post/%7Bid%7D
hope you guys can help me thanks
In Laravel we can use relationship to get related data. Here is the example to get user post comments:-
public function getComment()
{
$userId = Auth::user()->id;
$posts = Post::where('user_id', $userId)->with("post_comments")->get();
return $posts;
}
In Post model you need to add this
use App\Comment;
public function post_comments()
{
return $this->hasMany(Comment::class);
}
I hope this will help you to solve your problem with an easy way.
here is the code to retrieve all the comments of certain post by post->id
public function getComment($id) {
$comments = Comment::query()->where('post_id', $id)->get();
return $comments;
}
Make sure the Comment model class have table name
I edited my code and got this solutions, I add id on the get comment parameter
public function getComment($id)
{
$user = Auth::user();
$posts = $user->posts();
foreach ($posts as $key => $value) {
$posts[$key]->post_comments = PostComment::where('post_id', $id)->get();
}
return $posts;
}
public function getComment($id) {
$results = Post::with(['comments'])->where('post_id',$id);
$posts = $results->get();
}
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
public function comments() {
return $this->hasMany(Comment::class, 'post_id');
}
}
Related
I am trying to retrieve the data on my wishlist table, for a particular user, so far it only retrieves the first data on the table, just returning one array instead of the three in the table with same user id
public function getWishlistByUserId($id){
$wishlists = Wishlist::where('userId', $id)->get();
foreach($wishlists as $wishlist){
$products = Product::where('id', $wishlist->productId)->get();
return $products;
}
}
It happens because the foreach loop returns a value during the first iteration. Place your return statement outside the loop. Also you could improve your performence by making use of relationships.
An example could be:
// Product.php
public function wishlists()
{
return $this->hasMany(Wishlist::class);
}
// Your method
public function getWishlistByUserId($id)
{
return Product::whereHas('wishlists', function ($query) use ($id) {
$query->where('userId', $id);
});
}
Ideally this is n+1 situation
So i will suggest to use laravel relationship like:
in your whishlist model
public function product(){
return $this->hasMany(Product::class,'productId','id');
}
get data with relationship
public function getWishlistByUserId($id){
$wishlists = Wishlist::with('product')->where('userId', $id)->get();
}
I was finally able to get it working this way, i just pushed the result into an array, and then returned it outside the loop, thanks everyone for your help
public function getWishlistByUserId($id){
$wishlists = Wishlist::where('userId', $id)->get();
$wishlist = [];
foreach($wishlists as $wish){
$product = Product::where('id', $wish->productId)->get();
array_push($wishlist, $product);
}
return $wishlist;
}
This is my Controller method wherein I want to fetch posts by user id.
I also have relationship defined in User model
public function posts()
{
return $this->hasMany('Post','user_id','id');
}
UserController.php
use App\Post;
public function findPostsByUser($id){
$user = User::findOrFail($id);
$posts = $user->posts()->get();
return $posts;
}
But it is giving me 'Post' not found error. Can someone help on this.
In your Post model make sure you have the relation defined like this:
public function user()
{
return $this->belongsTo('App\User');
}
And change your User model to this:
public function posts()
{
return $this->hasMany('App\Post','user_id','id');
}
Change relation method to
use App\Post;
....
public function posts()
{
return $this->hasMany(Post::class,'user_id','id');
}
or
public function posts()
{
return $this->hasMany('App\Post','user_id','id');
}
If you wont to get only posts that case use this
public function findPostsByUser($id){
$posts = Post::where('user_id', $id)->get();
return $posts;
}
The second solution has 1 query, but first solution has 2 query in db.
Also you can do it this way
public function findPostsByUser($id){
$posts = Post::whereUserId($id)->get();
return $posts;
}
before i post this I've searched a lot for an answer but no result please forgive me my English not that good
i have Laravel app that contains :
User Model
public function Follow()
{
return $this->belongsToMany(Page::class,"follows","user_id","page_id");
}
Page Model
public function Posts()
{
return $this->hasMany(Post::class);
}
Post Model
public function Page()
{
return $this->belongsTo(Page::class);
}
In the homeController I've index method that should return the posts of the user's followed pages
$user->follow()->get();
this returned only the Pages collection, I couldn't get the Posts or access any
I need to access the posts and their properties, also if possible i need to count the post's likes.
thank you very much.
I have found an answer after trillion attempts
public function index()
{
$user = Auth::User();
$posts = [];
foreach ($user->follow as $key => $page)
{
foreach ($page->posts as $k => $post)
{
array_push($posts, $post);
}
}
//return $posts;
return view('home', compact('posts'));
}
I'm not able to access the likes count yet but i'll try the with('') method
I'll Update for any further Info
You're using the function follow() that returns a page!! Check your return statement
should be:
public function Follow()
{
return $this->belongsToMany(Follow::class,"follows","user_id","page_id");
}
I'm trying to make a RBAC in my own forum software.
For so far, the permissions work, but the problem is, when I want to add colors to usernames (what MyBB also has) something doesn't work and I don't understand it propperly.
So I have an ForumController with this code inside:
<?php
class ForumController extends \BaseController {
public function index()
{
$forums = Forums::orderBy('disp_order', 'asc')->get();
$categories = Categorie::orderBy('disp_order', 'asc')->get();
return View::make('index')->with('forums', $forums)->with('categories', $categories);
}
public function forum($name)
{
$forums = Forums::where('name', '=', str_replace('Forum-', '',str_replace('-', ' ', $name)))->first();
$categories = Categorie::orderBy('disp_order', 'asc')->get();
return View::make('forum')->with('forums', $forums)->with('categories', $categories);
}
public function categorie($name)
{
$categories = Categorie::where('name', '=', str_replace('Categorie-', '',str_replace('-', ' ', $name)))->first();
$threads = Thread::orderBy('date_posted', 'asc')->get();
return View::make('categorie')->with('categories', $categories)->with('threads', $threads);
}
public function thread($title)
{
$thread = Thread::where('title', '=', str_replace('Thread-', '',str_replace('-', ' ', $title)))->first();
$comments = Comment::orderBy('posted_at', 'asc')->get();
return View::make('thread')->with('threads', $thread)->with('comments', $comments);
}
}
Good, everything of that works.
But now I need to get the roles for users inside of the function thread.
I also have these models:
There is only an extend to Eloquent and the protected $table inside of these files.
The scheme of my role table looks like this:
I did hear somethig about belongsTo and hasMany, but I really don't understand it...
I want to be able to get the right color on the right user.
So the scheme of the user table:
I hope someone can help me out, because I'm looking for the answer a long time.
I'm using Laravel4
Kindest regards,
Robin
You're right, you need to add some relationships:
// In Comment.php, assuming that your comments table has a user_id field.
public function user()
{
return $this->belongsTo(User::class);
}
// In User.php
public function role()
{
return $this->belongsTo(Role::class);
}
Then adjust your controller to eager load these relationships.
$comments = Comment::orderBy('posted_at')->with('user.role')->get();
Now you can show the color next to a comment in your blade template like:
#foreach ($comments as $comment)
<p>Color: {{ $comment->user->role->colour }}</p>
#endfoeach
So i created an app with login users and users can post, now the post is working just fine but when i put a comment function, i get an error "Invalid argument supplied for foreach()"
i have this in my Post model
<?php
class Post extends Eloquent{
protected $fillable = array('email', 'password','title','content');
protected $table = 'posts';
public function User()
{
return $this->belongsTo('User');
}
public function Comment()
{
return $this->hasMany('Comment', 'post_id');
}
}
And in my Comment model
<?php
class Comments extends Eloquent {
public function post()
{
return $this->belongsTo('Post');
}
}
and i have this in my Controller
public function viewPost($id)
{
$post = Post::find($id);
$user = Auth::user();
$this->layout->content = View::make('interface.viewPost')->with('posts', $post )->with('users',$user);
}
and in my views
<section class="comments">
#foreach($posts->comments as $comment)
<blockquote>{{$comment->content}}</blockquote>
#endforeach
</section>
now when i try do run dd($posts->comment)
it returns a null because the comment table is empty. now what i want to know is why im getting this error? thanks for your help im just curious why this error is returning and i want to solve this one thanks
In your Post Model Comment is the function name not the comments and Comment method making relation with wrong name model under hasMany method call.
public function Comment()
{
return $this->hasMany('Comments', 'post_id');
}
Try to use
#foreach($posts->Comment as $comment)
If still inaccessible then try to eager loading.
like in your controller
$post = Post::with("comment")->find($id);