How to get forienkeys data in laravel models - php

I am implementing chat in my application using laravel. I have these Models:
`Users: id, name `
`Pages: id, user_id(foreign_key from Users table (id)), name`
`Posts: id, page_id(foreign_key from Pages table (id)), user_id(foreign_key from Users table (id)), body`
`Comments: id, post_id(foreign_key from Posts table (id)), user_id(foreign_key from Users table (id)), body`
I need to query followings
Get all posts of user with comments and with user
Get all posts of a page with comments and with user
I am using below query to get all posts of a page, but how can I include its comments and user details;
Page::with('post')->findOrFail($pageId)->post;
EDIT
USER Model: User.php
public function page() {
return $this->hasMany('Page');
}
public function post() {
return $this->hasMany('Post');
}
Page Model: Page.php
public function user()
{
return $this->belongsTo('User');
}
public function post() {
return $this->hasMany('Post');
}
Post Model: Post.php
public function user()
{
return $this->belongsTo('User');
}
public function page() {
return $this->belongsTo('Page');
}
public function comments() {
return $this->hasMany('Comment');
}
Comment Model: Comment.php
public function user()
{
return $this->belongsTo('User');
}
public function post() {
return $this->belongsTo('Post');
}

As your relationships are not that clear to me, i can only provide some hints where to look.
Getting posts of a user with comments sounds like laravel query scopes: http://laravel.com/docs/5.1/eloquent#query-scopes
You may also query for relationship existence: http://laravel.com/docs/5.1/eloquent-relationships#querying-relations
And Lazy Eager Loading could also help to retrieve the necessary instances.

Related

Laravel 5.7: Database query returning no values

I'm trying to retrieve a group of post IDs from my likes table where the user ID is equal to the ID stored in the Auth Session.
So far I have tested retrieving data in multiple ways, if I select all the likes from the table it works fine, the auth ID retrieved from the session is the same as the one stored in the likes table so should produce a match and return data.
Here's the code I'm currently working with:
public function index()
{
$userid = Auth::id();
$userLikes = likes::all()->pluck('post_id')->where('user_id', $userid);
dd($userLikes);
}
The columns names within the table are as follows:
id
created_at
updated_at
user_id
post_id
I have tried this method of writing the query however am experiencing the same issue, no errors and no data.
DB::table('likes')->pluck('post_id')->where('user_id', $userid)->toArray();
I am looking to have an array of post ids for the posts liked by the logged in user so that it can be passed into the view.
Thanks in Advance
If you've created User, Post, and Like models with the appropriate relationships, you can do the following:
$ids = auth()->user()->likes->pluck('post_id')->toArray();
The model's would have relations defined as:
// User.php
public function likes()
{
return $this->hasMany(Like::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
// Like.php
public function user()
{
return $this->belongsTo(User::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
// Post.php
public function user()
{
return $this->belongsTo(User::class);
}
public function likes()
{
return $this->hasMany(Like::class);
}
Alternatively, using the query builder:
DB::table('likes')->where('user_id', auth()->id())->get('post_id')->toArray();

Select specific column in laravel eloquent's with method

I am using laravel 5.6 and i want to get user posts with comments (only id field)
User Model
public function posts()
{
return $this->hasMany('App\Post');
}
Post Model
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
Comment Model
public function post()
{
return $this->belongsTo('App\Post');
}
In my controller i am using this code to get user posts with their comments
$posts = $request->user()->posts()->with(['comments' => function($query) {
$query->select(['id']);
}]);
But its not working...
When i comment $query->select(['id']); it works fine but returns Comment model all fields. I want to only select id field.
What i am missing here?
You also have to select the foreign key column (required for matching the results):
$posts = $request->user()->posts()->with('comments:id,post_id');
If you want to only one column, you can use ->pluck('id')
https://laravel.com/docs/5.6/collections#method-pluck

Laravel defining relationship

Am still new to laravel
I have the following tables
user
id
first_name
last_name
educations
id,
user_id //references user id
type
Now in my user model i would like to get a specific users educations which can be many
so a user can have many educations but each education belongs to a single user.
So in my user model i have
public function education()
{
return $this->hasMany('App\ApplicantEducation','id','user_id');
}
In my Education model i have
public function user()
{
return $this->belongsTo('App\User','user_id','id');
}
But the above fails, I cannot retrieve user specific educations
Where am i going wrong?
try this:
in User Model:
public function educations()
{
return $this->hasMany('App\ApplicantEducation', 'user_id');
}
in Education Model:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
Change return $this->hasMany('App\ApplicantEducation','id','user_id');
to return $this->hasMany('App\ApplicantEducation','user_id', 'id'); you also ommit the id and user_id.
As your foreign_key is well formed, you can also rwite this simple code,
class User{
public function education()
{
return $this->hasMany('App\ApplicantEducation');
}
}
Class Educations{
public function user()
{
return $this->belongsTo('App\User');
}
}
Here,
$this->hasMany('App\ApplicantEducation','id','user_id');
In above statement first argument should be Model second should be foreign key and the third one is any other key from Education model.
Here, second and third arguments are not mandatory.
In User Model
class User...{
public function education()
{
return $this->hasMany('App\ApplicantEducation');
}
In Education Model
public function user()
{
return $this->belongsTo('App\User');
}
Here, additional parameters are not mandatory might be your addition parameters creates issue,
and now you can retrieve your user with Education by
$user = User::with('education')->get();
This can retrieve all the users with their education.
I hope it helps,Thank you, Happy coding.
You should try this:
Education Model
public function user()
{
return $this->belongsTo('App\User','user_id);
}
User Model
public function education()
{
return $this->hasMany('App\ApplicantEducation');
}

Laravel - Eloquent: get posts from user with users post table

I searched a lot but could not find any answer about it, so I hope you could help me!
I have three tables: posts, users and post_users.
Post_users contains two columns: user_id and post_id.
I need to get all posts by an user with Eloquent. Any ideas?
Model User:
public function posts()
{
return $this->belongsToMany('App\Post', 'post_users', 'user_id', 'post_id');
}
Model Post:
public function users()
{
return $this->belongsToMany('App\User', 'post_users', 'post_id', 'user_id');
}
Try:
$user = User::find($id);
$allpost = $user->posts()->get();
var_dump($allpost);
The Laravel docs cover this pretty well but I had an issue with it when I first started as well. Check out Laravel Relationships for the fully write up.
// Inside your Post model
public function user() {
return $this->belongsTo('App\User');
}
// Inside your User model
public function posts() {
return $this->hasMany('App\Posts');
}
You can then create a query:
$posts = User::find(1)->posts;
Or you can filter it further..
$posts = User::find(1)->posts()->where('active', 1)->get();
You may need to change your paths for the hasMany() and belongsTo() if your model location and names are different.
As you wish. Relation between User and Post is many-to-many
- Defined relation
// In User model
public function posts(){
return $this->belongsToMany(Post::class);
}
// In Post model
public function users(){
return $this->belongsToMany(User::class);
}
- Table structure
- users
id
- posts
id
- post_user
user_id
post_id
- Get all post by a user
$posts = User::find($user_id)->posts
If you donot have relationship built, try this. However building relationships is preferred. PostUsers and Posts are assumed models of post-users and posts tables, and post as column of the posts table. this gives the posts of logged in user, but not tested.
$postusers=PostUsers::where(['user_id'=>Auth::user()->id])->get();
foreach($postusers as $postuser)
{
$posts=Posts::where(['post_id'=>$postuser->post_id)]->get();
foreach($posts as $post)
{
print_r($post->post);
}
}
Try this
From Controller :
dd(Auth::user()->posts);
App/User
public function posts()
{
return $this->belongsToMany('App\Entities\posts', 'post_users', 'user_id', 'post_id');
}
make relationship with post model on the user model:
public function posts()
{
return $this->hasMany(Post::class);
}
make relationship with user model on the post model:
public function User()
{
return $this->belongsTo(User::class);
}
in controller or Wherever you use:
$userPosts = User::find($user->id)->posts->where('status', 1);

`Trying to get property of non-object` using `hasManyThrough` relationship laravel 5

I am trying to develop a blog using Laravel 5 in which i have to show comment along with user on post.
Here is my database table schema.
User
id
name
Posts
id
post_content
user_id
Comments
id
comment
user_id
post_id
Here is my User Model
public function posts()
{
return $this->hasMany('App\Models\Posts');
}
public function comments(){
return $this->hasManyThrough('App\Models\Comments','App\Models\Posts');
}
Here is my Posts Model
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function comments(){
return $this->hasMany('Ap\Models\Comments');
}
Here is my Comment Model
public function posts()
{
return $this->belongsTo('App\Models\Posts');
}
public function user(){
return $this->posts->name;
}
Here is my code how i am accessing user name
$comments = Comments::find(1);
$comment['comment'] = $comments->comment;
$comment['user_name'] = $comments->name;
$comment['post_id'] = $comments->posts->id;
may be i am not getting in right direction? if i am doing right then why it is not working.
In laravel 5 you do not call the model as you are doing. since the models are stored in the app folder just call like. Plus I think you need to define the relationship
class User extends Model {
public function phone()
{
return $this->hasOne('App\Phone');
}
}
class Phone extends Model {
public function user()
{
return $this->belongsTo('App\User');
}
}
$phone = Phone::find(1);
For the case of foreign keys and more regarding the Eloquent relationships in laravel 5 just follow the documentation on the laravel website. Make sure to look at dynamic properties of that are allowed by eloquent
http://laravel.com/docs/5.0/eloquent

Categories