Laravel Retrieve related model through pivot table - laravel-5

So i'm a bit confused with this situation, I have the current relations:
User hasmany Favourite
favourites references to a Recipe model
favourites is a pivot table but when I retrieve the favourites for a given user like:
$user->favourites
i get the favourite with the pivot data, but I want to get the fields of the recipe
Recipe.php:
public function favourites()
{
return $this->hasMany('App\Favourite');
}
User.php:
public function favourites()
{
return $this->hasMany('App\Favourite');
}
Favourite.php:
public function user()
{
return $this->belongsTo('App\User','user_id');
}
public function recipes()
{
return $this->belongsTo('App\Recipe','recipe_id');
}
EDIT : there was no problem at all, just needed to call:
#foreach($user->favourites as $favourite)
{{ $favourite->recipe->name }}
#endforeach

You need to set your relation to Has Many Through instead of just has Many.
https://laravel.com/docs/5.2/eloquent-relationships#has-many-through
Recipe.php:
public function favourites()
{
return $this->hasManyThrough('App\Favourite', 'App\User');
}
User.php:
public function favourites()
{
return $this->hasManyThrough('App\Favourite', 'App\Receipe');
}
Favourite.php:
public function user()
{
return $this->hasManyThrough('App\User','App\Receipe');
}

Related

Trying to get property 'designation_name' of non-object in Laravel 8

I want to show the user role from my user role table, but I can't.
User.php
public function role()
{
return $this->belongsTo('App\Models\Designation');
}
UserController
public function index()
{
$user = User::all();
return view('dashboard2', compact('user'));
}
View
<h1>{{ Auth::user()->role->designation_name}}</h1>
You actually should have shared more details about the relationships. But I will give an answer based on an assumption. It seems like there is a one-to-one relationship betwen User and Role as well as Role and Designation. So you want to reach designation from user. Based on that:
//User.php
public function role()
{
return $this->hasOne(Role::class);
}
//Role.php
public function user()
{
return $this->belongsTo(User::class);
}
public function designation()
{
return $this->hasOne(Designation::class);
}
//Designation.php
public function role()
{
return $this->belongsTo(Role::class);
}
// Controller
public function index()
{
// If you need only the auth user's data, you don't
// need adding relationships into the query.
$users = User::with('role.desgination')->all();
return view('dashboard2', compact('users'));
}
// View
// For auth user:
// I haven't used this way before,
// but technically it should work.
auth()->role()->designation()->name;
// For users collection:
// Make sure you added the query to the controller.
#foreach($users as $user)
$user->role->desgination->name
#endforeach

How to get multiple relationships Data in My Laravel Vue Project

I have a 3 model "User","Review","ReviewReplay"
in user Model
public function reviews()
{
return $this->hasMany('App\Models\Review');
}
public function reviewReplys()
{
return $this->hasMany('App\Models\ReviewReply');
}
In Review Model
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function reviewReplys()
{
return $this->hasMany('App\Models\ReviewReply');
}
in Review Replay Model
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function review()
{
return $this->belongsTo('App\Models\Reviews');
}
in My Controller
public function getReview($id)
{
$review= Review::where('product_id',$id)->with('user','reviewReplys')->paginate(10);
return response()->json($review);
}
Now here I run Review foreach loop and here I need review.reviewReplay.user information. How I Get The Review Replay User information inside Review Foreach loop.
You can do it as below.
$review= Review::where('product_id',$id)->with(['reviewReplys.user'])->paginate(10);
with(['reviewReplys.user']) --> it will make connection between Review model to reviewReplys model +
reviewReplys model to User model

Laravel One to Many relation with 2 primary keys

I've 2 tables
Users table
id
name
...
Chats table
id
from_id // fk - id on users, the user sent the message
to_id // fk - id on users, intended user
message_body
Now, I'm trying to set up One to Many relation where user has many chat messages but a chat message has two user. from and to user
How can I define this relationship?. I have to user eager loading.
I tried to use Compoships but it didn't work.
My code
User Model
public function chats() {
return $this->hasMany(Chat::class, ['from_id', 'to_id'], 'id');
}
Chat Model
public function user() {
return $this->belongsTo(User::class, ['from_id', 'to_id'], 'id');
}
public function chats() {
return $this->hasMany(Chat::class, 'from_id', 'id') + $this->hasMany(Chat::class,'to_id','id');
}
public function userFrom() {
return $this->belongsTo(User::class, 'from_id', 'id');
}
public function userTo() {
return $this->belongsTo(User::class, 'to_id', 'id');
}
Why don't you do something like that?
On your User model, set up two relationships like this:
public function chatsFrom() {
return $this->hasMany('App\Chat', 'from_id');
}
public function chatsTo() {
return $this->hasMany('App\Chat', 'to_id');
}
Then, on your Chat model, also set up two relationships, one to from and another to to, both referencing a User model. Like this:
public function fromUser() {
return $this->belongsTo('App\User', 'from_id');
}
public function toUser() {
return $this->belongsTo('App\User', 'to_id');
}
This way, you can access the relationships using something like this:
$user->chatsFrom();
$user->chatsTo();
$chat->fromUser();
$chat->toUser();

lumen/laravel Eloquent hasManyThrough 3 models relation

I try to acomplish a relation with 3 models:
Cities.php //table cities
id
name
Neighbourhoods.php //table neighbourhoods
id
name
city_id
Blocks.php //table blocks
id
name
neighbourhood_id
My models looks like this:
Cities.php
public function neighbourhoods()
{
return $this->hasManyThrough('App\Neighbourhoods', 'App\Blocks', 'neighbourhood_id', 'city_id', 'id');
}
Neighbourhoods.php
public function blocks()
{
return $this->hasMany('App\Blocks', 'neighbourhood_id', 'id');
}
Blocks.php
public function neighbourhoods()
{
return $this->belongsToMany('App\Neighbourhoods', 'neighbourhood_id', 'id');
}
The result shoud be:
results
city1:
neighbourhoods:
neighbourhood1:
block1
block2
block3
neighbourhood2
block1
block2
city2:
neighbourhoods:
neighbourhood1:
blocks:
block1
block2
block3
neighbourhood2:
blocks:
block1
block2
Calling the results:
return Blocks::with('neighbourhoods')->get();
I know that my models are not properly named. City (singular), Neighbourhood (singlar), Block (singular) but passing parameters shoud work.
I just can't figure our why it does not work.
RELATIONSSHIP SOLUTION based on #Gaurav Rai's response
First of all, my models are wrong named. Please condider naming your database using plurals for example: cities, neighbourhoods, blocks and your models singular for example: City.php, Neighbourhood.php and Block.php
Based on my problem, the solution is:
Cities.php
public function neighbourhoods()
{
return $this->hasMany('App\Neighbourhoods', 'city_id', 'id');
// because my model is called Cities.php,
// the function will look by default
// for the column cities_id in neighbourhoods table,
// thats why we need to specifiy city_id column
}
public function blocks()
{
return $this->hasManyThrough('App\Blocks', 'App\Neighbourhoods', 'city_id', 'neighbourhood_id', 'id');
}
Neighbourhoods.php
public function cities()
{
return $this->belongsTo('App\Cities', 'city_id', 'id');
}
public function blocks()
{
return $this->hasMany('App\Blocks', 'neighbourhood_id','id');
}
Blocks.php
public function neighbourhoods()
{
return $this->belongsTo('App\Neighbourhoods', 'neighbourhood_id');
}
Calling the relation:
return Cities::with(['neighbourhoods', 'blocks'])->get();
I think your relationships are not well defined:
Cities.php
public function neighbourhoods()
{
return $this->hasMany('App\Neighbourhoods');
}
public function blocks()
{
return $this->hasManyThrough('App\Neighbourhoods', 'App\Blocks');
}
Neighbourhoods.php
public function blocks()
{
return $this->hasMany('App\Blocks');//by default it will consider id
}
public function city()
{
return $this->belongsTo('App\City');
}
Blocks.php
public function neighbourhoods()
{
return $this->belongsTo('App\Neighbourhoods');
}

Laravel 4 Eloquent relations query

I have a project with main table 'Qsos' and bunch of relations. Now when I try to create advanced search I don't really know how to query all relations at the same time. Qso model has following:
public function band()
{
return $this->belongsTo('Band');
}
public function mode()
{
return $this->belongsTo('Mode');
}
public function prefixes()
{
return $this->belongsToMany('Prefix');
}
public function user()
{
return $this->belongsTo('User');
}
public function customization() {
return $this->hasOne('Customization');
}
Then I have SearchController with following code that has to return collection of all Qsos following required conditions:
$qsos = Qso::withUser($currentUser->id)
->join('prefix_qso','qsos.id','=','prefix_qso.qso_id')
->join('prefixes','prefixes.id','=','prefix_qso.prefix_id')
->where('prefixes.territory','like',$qTerritory)
->withBand($qBand)
->withMode($qMode)
->where('call','like','%'.$input['qCall'].'%')
->orderBy('qsos.id','DESC')
->paginate('20');
And then in view I need to call $qso->prefixes->first() and $qso->prefixes->last() (Qso and Prefix has manyToMany relation) but both return null. What is wrong?
Here is the eloquent code that I found working but taking VERY long time to process:
$qsos = Qso::withUser($currentUser->id)
->with('prefixes')
->withBand($qBand)
->withMode($qMode)
->where('call','like','%'.$input['qCall'].'%')
->whereHas('prefixes', function($q) use ($qTerritory) {
$q->where('territory','like',$qTerritory);
})
->orderBy('qsos.id','DESC')
->paginate('20');

Resources