Laravel Intermediate relations data error - laravel

Here is my RecentViewController file code:
$contents = RecentView::where('user_id', $loggedUser)
->with('posts')
->with('profile')
->paginate(12)->toArray();
and my RecentView model code is as follows:
public function posts()
{
return $this->hasOne('App\FeedPost', 'id', 'post_id');
}
public function profile()
{
return $this->belongsTo('App\Profile', 'user_id', 'id');
}
the data i receive after running this code shows logged in users details instead of posts users detaisl. how can i change retreiving posts users data instead of logged users data?

I guess you are trying to get the user of the post
In order to get posts users detail you need to move profile relation into Post model. I hope there's a user_id in posts table. then get profile relationship of post model with dot notation as follows
$contents = RecentView::where('user_id', $loggedUser)
->with('posts.profile')
->paginate(12)->toArray();

Related

Get paginated many to many records in laravel

for my app I made it so an user can favorite venues, this relationship between venues and user is many to many, problem is I don't know how to get favorite_venues paginated.
Right now what I'm doing is getting user with favorite_venues but that doesn't seem right to me, is there a way to get favorite venues paginated directly without having to get the user.
What I'm currently doing:
public function getFavorites($request)
{
$user = User::with(['favoritevenues','favoritevenues.category'])->findOrFail(1);
return $user;;
}
I set relationships like this:
User Model
public function favoritevenues()
{
return $this->belongsToMany('App\Models\Venue', 'favorite_venues', 'user_id', 'venue_id')->withTimeStamps();
}
Venue Model
public function favorites()
{
return $this->belongsToMany('App\Models\User', 'favorites', 'venue_id', 'user_id')->withTimeStamps();
}
Thanks in advance
you can do:
Venue::whereHas('favorites', function ($q) {
return $q->where('id', 1);
})->paginate(5);
This will get and paginate all the venues which are the favourites of user with id 1

Getting 2 lots of relationship data from a Laravel collection with Yajra Datatables

I am trying to get my Yajra Datatable working correctly but struggling.
Basically I want to get all clients appointments in which the client belongs to the logged in user. I then want to access the Client name and then the appointment data. I have used the following to get the appointment data
$user = User::find(Auth::user()->id);
$data = $user->clients()->with('appointments')->get()->pluck('appointments')->flatten();
return Datatables::of($data)
->make(true);
This allows me to show a row for each appointment that exists for the user-owned clients appointments. But how can I also access the clients name from this?
I have tried many different ways but if I use something like
$data = $user->clients()->with('appointments')->get();
I can access all of the data I need but it shows the existing clients in each row, not all appointments owned by the clients.
My setup is
User Model
public function clients(){
return $this->hasMany(Client::class);
}
public function appointments()
{
return $this->hasManyThrough(Appointment::class, Client::class);
}
Client Model
public function appointments(){
return $this->hasMany(Appointment::class);
}
public function users(){
return $this->belongsTo(User::class);
}
Appointment Model
public function client(){
return $this->belongsTo(Client::class);
}
Thank you
You might be looking for whereHas:
$appointments = Appointment::with('client')
->whereHas('client.users', function ($query) use ($user) {
$query->where('users.id', $user->id)
})
->get();
This translates to: "Give me all the appointments that belong to clients of a specific user".
Just a suggestion, it might be wise (not required at all) to alter your database structure to something more flexible. What if you for instance keep track in you appointment which user is present?
appointments
- user_id
- client_id
This would make your query a bit simpler
// In User
public function appointments()
{
return $this->hasMany(Appointment::class);
}
$user->appointments()->with('client')->get();
You could go even further by making the relation between User and Appointment, Client and Appointment many to many so you could have appointments with more than one user and/or client.

How to use where condition in laravel eloquent

I am using laravel eloquent. I have fetched data from two table using eloquent.
I have post table and chat table. For post table I have model Post.php and for chat table I have model Chat.php. Here is the the eloquent relation I have created to fetch chat for individual post for a user.
in Post.php
public function TeamMessage()
{
return $this->hasMany('App\Chat','post_id');
}
And in Chat.php
public function ChatRelation()
{
return $this->belongsTo('App\Post');
}
it is working perfect. But this relation fetch all messages for a specific post. I want to fetch all unread message from chat table. I have a column named unread in chat table.
Now my question is how I can fetch only unread message for a specific post.
While the other answers all work, they either depend on scopes (which are very useful in many circumstances) or on you having already instantiated an instance of $post, which doesn't let you eager load multiple posts with their messages.
The dynamic solution is this, which will let you fetch either 1 or more posts and eager load their messages with subquery:
$posts = Post::with(['TeamMessage' => function ($query) {
$query->where('unread', true); // This part applies to the TeamMessage query
}])->get();
See in documentation
Edit:
If you, however, want to filter the posts, to only show those that have unread messages, you need to use whereHas instead of with:
$posts = Post::whereHas(['TeamMessage' => function ($query) {
$query->where('unread', true); // This part applies to the TeamMessage query
}])->get();
More in the documentation.
You can also chain whereHas(...) with with(...).
For querying relationships, you have to call them as functions instead of properties, like this:
$unreadPosts = $post->TeamMessage()->where('unread', true)->get();
For more information on this you can take a look at the docs.
You need to create a local scope on your model, information on local scopes can be found here: https://laravel.com/docs/5.6/eloquent#local-scopes
public function scopeUnread($query)
{
return $query->where('unread', 1);
}
Then in your controller/view
$unread = $yourmodel->unread()
First I would change your relation names to the name of the entity in lower case:
in Post.php
public function chats()
{
return $this->hasMany('App\Chat','post_id');
}
And in Chat.php
public function post()
{
return $this->belongsTo('App\Post');
}
public function scopeUnread($query)
{
return $query->where('unread', 1);
}
Then you can use
$post->chats()->unread()->get();

Relationship with user condition

I have a follow system that works like Twitter's follow (you follow other people and get updates from them).
I have this relationship set in my User.php model:
public function follows()
{
return $this->hasMany('App\Follow');
}
This obviously gets all records of users who follow this person.
However, when displaying the person's profile page, I want to get a relationship that checks if a follow record exists given the user ID.
Something like:
public function userFollow()
{
return $this->hasOne('App\Follow')->where('user_id', Auth::user()->id);
}
So now my profile page query looks like this:
$user = User::where('username', $username)
->with('userFollow')
->first();
This works as long as the user is logged in. If the user isn't logged in, the page gives me this error:
ErrorException in User.php line 28: Trying to get property of
non-object
How do I fix this? What is the proper way of using conditions in relationships?
This is because if user is logged out then Auth::user() is null, because user session has ended. Auth::user() is no more object, so you can't get the id from a null object.
Here you can do something like that
public function userFollow()
{
$userId = Auth::user() ? Auth::user()->id : $this->id;
return $this->hasOne('App\Follow')->where('user_id', $userId);
}
then it will not look for authenticated user, it will just get the particular user table's id.
The proper way of using conditions in relationships is using Constraining eager loads
public function userFollow()
{
return $this->hasOne('App\Follow');
}
And,
if(Auth::check())
{
$user = User::where('username', $username)
->with(['userFollow'=>function($query)
{
$query->where('user_id', Auth::user()->id);
}]);
->first();
}

Laravel orm Order by custom attribute

In my user model I have added custom attribute get number of post user have created.
I can successfully get that but when I have try to order by it give error.
1054 Unknown column 'posts' in 'order clause'
Can you let us know what is the Eloquent query you're running? Also make sure that the name of the table you're using is correct.
EDIT:
Does the posts column exist in the users table? Or are you trying to get all the posts from the Post Model and order the posts by their name in descending order?
If that is what you want to do then you would need to go to your User Model and set up your relationship with posts.
In User Model create this method:
public function posts() {
return $this->hasMany('Post'); // Post would be the name of the Posts Model
}
In Post model do this:
public function user() {
return $this->belongsTo('User'); // Where User is the name of the Users Model
}
Then according to the Laravel documentation you could do someonething like this with the query:
$users = User::with(array('posts' => function($query)
{
$query->orderBy('name', 'desc'); // assuming that 'name' would be the column in the posts table you want to sort by
}))->take(5)->get();
I hope I am correct and this helps and that solves your issue.

Resources