Here are my tables
Posts
id | name | created_At
Comments
id | comment | post_id | created_at
Post Model
function comments(){
return $this->hasMany('App\Models\Comment','id','post_id');
}
PostsController
function index()
{
Post::with('comments')::get();
}
Now how can i get list of all posts along with comments?
I am trying to match post_id in the child table.
In Your Post Model:
public function comments()
{
return $this->hasMany('App\Model\Comment');
}
In Your Post Controller :
use Illuminate\Http\Request;
function index(Request $request)
{
$posts=Post::with('comments')->get();
// in json
return response()->json($posts);
// in your view
//return view('viewname')->with('posts',$posts);
}
Related
This is my User Item Pivot Table
| item_id | user_id | rate |
and i have defined many to many relation in both User and Item Model
This is my User Model
public function items()
{
return $this->belongsToMany(Item::class, 'item_user')->withPivot('rate');
}
This is my Item Model
public function users()
{
return $this->belongsToMany(User::class, 'item_user')->withPivot('rate');
}
This is My Controller.Suppose I have item_id.I want to find rate of where user and item_id id match.
public function findRate(Request $request){
$user=User::where('id',auth()->user()->id)->first();
$item_rate=$user->items->where('item_id', '1')->first();
dd($user);
return response()->json([
'item_rate'=>$item_rate,
]);
}
I tried like this but Error say Property [pivot] does not exist on this collection instance
$item_rate=$user->items->where('item_id', '1')->pivot()->rate;
Try this
$item_rate=$user->items()
->where('item_id',1)
->first()
->pivot
->rate;
Message Tables Column is
| messages_id(pk) | user_id | target_id | message | created_at
User_id has sender user's id. Target_id has receiver user's id
And simple user table has relation to MessageTable by HasMany.
public function message()
{
return $this->hasMany('App\Model\TableModel\Message', 'user_id', 'user_id');
}
I want to get Userdata and each last message from user_id=[1,2,3,4] to target_id = 5.
So I tried this
User::WhereIn(user_id, [1,2,3,4])
->with(['message' => function ($query) {
$query->Where('target_id', 5)->orderBy('messages_id', 'desc)->first();
}])->get();
But this query return User's data and one user last message.
How do I get users last message using hasMany ?
your hasMany relation is incorrect:
the third argument should be the primary key of the current model:
public function message()
{
return $this->hasMany('App\Model\TableModel\Message', 'user_id', 'id');
}
anyway, to get the last message, I recommend building a new relation using hasOne relation:
public function lastMessage()
{
return $this->hasOne('App\Model\TableModel\Message', 'user_id', 'id')->latest();
}
now, you can use this new relation like:
User::WhereIn(user_id, [1,2,3,4])
->with(['lastMessage' => function ($query) {
$query->Where('target_id', 5);
}])->get();
I am learning Laravel and there is one thing I cannot solve.
What do I have:
Table of Users, Posts, Comments and corresponding Models
User.php:
public function comments() { return $this->hasMany(Comment::class); }
public function publishComment(Comment $comment)
{
$this->comments()->save($comment);
}
Post.php:
public function comments() { return $this->hasMany(Comment::class); }
Comment.php:
public function post() { return $this->belongsTo(Post::class); }
public function user() { return $this->belongsTo(User::class); }
What do I want?
Since I have Blog, one logged user can create many posts (this works).
But same logged user can create many comments to one post. (User has many comments, post has many comments).
Tables:
User: | id | name | email | password
Comment: | id | user_id | post_id | body
Post: | id | user_id | title | body
What have I tried?
I created controller
CommentsController:
class CommentsController extends Controller
{
public function store(Post $post)
{
$this->validate(request(), ['body' => 'required|min:2']);
auth()->user()->publishComment(
new Comment(request('body'));
);
return back();
}
And in my blade file I simply want $comment->user->name (get name of user who does the comment belongs to)
Error I get:
Trying to get property of non-object
<?php echo e($comment->user->name); ?>
Any help would be appreciated.
You need a Polymorphic Relations Relationship.
Table Structure
posts
id - integer
title - string
body - text
user_id - integer
users
id - integer
name - string
email - string
password - string
comments
id - integer
body - text
commentable_id - integer
commentable_type - string
Into commentable_id you save the User id or the Post id.
Into commentable_type you save the User Model or Post Model.
And also you can have another table using comments table.
Models
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get all of the owning commentable models.
*/
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
/**
* Get all of the post's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
class User extends Model
{
/**
* Get all of the users's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
See the docs to get more details.
In this video you have a good explanation https://youtu.be/lePjXdMC6aM
You can simply do this in your view.blade.php:
// Here I am assuming you have a $post variable that contains your blog post.
<ul>
#foreach ($post->comments as $comment)
<li>{{ $comment->user->name }}</li>
#endforeach
</ul>
This will loop over all the comments that you have for your blog post and display the owner's name, hopefully this helps.
Try this if you need just the name of the person who created comment.
{{ $post->user->name }}
Or
user->name); ?>
it is possible to get all details (user, posts, postimages) within one collection / json?
user->hasmany(posts)
post->hasmany(postimage)
user:
id | name
post:
id | user_id | text
postimage:
id | post_id | imgpath
user model:
public function posts() {
return $this->hasMany('App\posts')->orderBy('id', 'ASC');
}
posts model:
public function images(){
return $this->hasMany('App\postsimages');
}
get all posts from user works fine:
$myposts = users::find(Auth::user()->id)->posts;
i'm able to get all images from a post within a loop
foreach($myposts as $mypost) {
$postimages = $mypost->images;
}
what i want is to get all posts, images without the loop e.g
$myposts = users::find(Auth::user()->id)->posts->images
thanks
Yes, use hasManyThrough relationship.
posts model:
public function images()
{
return $this->hasMany('App\postsimages');
}
user model
public function posts()
{
return $this->hasMany('App\posts')->orderBy('id', 'ASC');
}
public function images()
{
return $this->hasManyThrough('App\posts', 'App\postsimages');
}
then
$postimages = Auth::user()->images;
Sorry for the noob question, but I am not able to make eager loading work, and instead getting: Trying to get property of non-object in my view (index.blade.php below).
Users table
id | first_name | other_columns
Credits table
id | recipient | other_columns
recipient is id from the Users table.
Credit.php
class Credit extends Model {
public function recipient() {
return $this->belongsTo('App\User', 'recipient');
}
}
User.php
class User extends Model {
public function credits() {
return $this->hasMany('App\Credit', 'recipient');
}
}
CreditController.php
class CreditController extends Controller {
public function index() {
$credits = Credit::with('recipient')->get();
return view('pages.credits.index')->withCredits($credits);
}
}
index.blade.php
#foreach($credits as $credit)
{{ $credit->recipient->first_name }}
#endforeach
What am I missing?
I solved this by changing in my Credit Model:
public function recipient() {}
into
public function user() {}