Laravel getting realtionship with auth() - laravel

I have the following relationship in User.
public function partner()
{
return $this->hasOne('App\Partner','partner_id');
}
And I am accessing that relationship
auth()->user()->partner()->name
But it gives me exception where name is available in partners table:
Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$name`
And the user object from auth()->user()->partner() is also empty.
What am I missing?

auth()->user()->partner() returns the relation binding, not the model itself.
try auth()->user()->partner->name instead.

First, ensure you setup the right relationship:
User.php
public function partner()
{
return $this->hasOne('App\Partner');
}
Partner.php
public function user()
{
return $this->belongsTo('App\User');
}
To access the user's partner:
// Get the user's Partner instance:
$partner = auth()->user()->partner;
// Access the user's partner properties:
$partner_name = auth()->user()->partner->name;
Also, check that your partners table has the column user_id.

I think you are doing it wrong, All you have to do is that to change :
public function partner()
{
return $this->hasOne('App\Partner','partner_id');
}
to
public function partner()
{
return $this->belongsTo('App\Partner');
}
A user belongs to a partner, Cause partner is a meta table.

Related

Laravel HasMany relation with parameters

i have a relation between User model and Friend model
User.php
public function friends()
{
return $this->hasMany(Friend::class);
}
the relation actually returns all the records where the foreign key column (user_id) between User and Friend equals the current user's id but i want to return also the records where current user's id is in another column in friends table which's name is friend_id, this is my try
public function friends()
{
return $this->hasMany(Friend::class,'user_id','friend_id');
}
it's actually not returning the correct records
I don't think there is a direct way to that but you could try making 2 relations and merge them into one relation
public function friends() {
return $this->hasMany(Friend::class);
}
public function additionalfriends() {
return $this->hasMany(Friend::class, 'friend_id');
}
public function allfreinds() {
return $this->friends->merge($this->additionalfriends);
}
another solution you might try is
public function friends()
{
return Friend::where(function($query) {
$query->where('user_id',$this->id)
->orWhere('friend_id',$this->id);
});
}

laravel model relationship seems backwards compared to docs

So I am setting up a one to one relationship between MyModel and the users table.
MyModel obviously has a user_id column to tie back to the users.
However - when i go to setup the relationship in MyModel I have to set it up in a way which seems backward!
This is in MyModel:
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
}
Why Am i having to set the opposite foreign and local keys... ? Am i missing something?
Do it like this
class MyModel {
public function user()
{
return $this->belongsTo('App\User');
}
}
class User {
public function myModel()
{
return $this->hasOne('App\MyModel');
}
}
And that should work as intended (one to one) relationship

Updated: Why relationship works when user is Admin, but won`t when Regular user?

I have 3 models: User, Role and Currency. I am confused about relationship between them.
Then User is Admin this works:
Auth::user()->currency->symbol)
When regular User I get error:
Trying to get property of non-object
if dd(Auth::user()) it show user, but cant access to relationship with model Currency. Why it is so?
User model relationship:
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id');
}
Currency model relationship:
public function created_by()
{
return $this->belongsTo(User::class, 'created_by_id');
}
If you need extra information, let me know.
User model
public function currency()
{
return $this->belongsTo(Currency::class);
}
Currency model
public function users()
{
return $this->hasMany(User::class, 'created_by_id');
}
Going with an assumption that your User model has an attribute currency_id
$this->belongsTo(TABLE, FORIEGN KEY, TABLE KEY);
refer this
User model
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id', 'id');
}
Currency model
public function users()
{
return $this->hasMany(User::class, 'created_by_id', 'id');
}

Laravel Relationship not working on server

My project is working fine on local host, but on the server, getting error only on lesson page.
Subject Model is
class Subjects extends Model
{
public function category()
{
return $this->belongsTo('Lea\Category');
}
public function lesson()
{
return $this->hasMany('Lea\Lessons');
}
public function chapter()
{
return $this->hasMany('Lea\Chapters');
}
public function users()
{
return $this->belongsToMany('Lea\User', 'subject_user', 'subject_id', 'user_id');
}
}
And Lesson Model is
class Lessons extends Model
{
public function chapter()
{
return $this->belongsTo('Lea\Chapters');
}
public function subject()
{
return $this->belongsTo('Lea\Subjects', 'subject_id');
}
public function category()
{
return $this->belongsTo('Lea\Category');
}
}
My controller lessons has method index like below.
public function index()
{
$lessons = lessons::orderBy('id', 'asc')->paginate(5);
return view('admin.lessons.index')->withLessons($lessons);
}
The way i am calling subject name is show below. first subject is relationship subject and 2nd subject is the field name where subject name saved in db. using foreach to get data like:
#foreach ($lessons as $lesson)
{{$lesson->subject->subject}}
#endforeach
subjects table schema is
id
subject
admin_id
users_id
category_id
created_at
updated_at
lessons table schema is
id
title
slug
category_id
subject_id
chapter_id
users_id
content
image
That's more like it ;)
Just edit how you are passing the object to the following:
...
return view('admin.lessons.index')->with(compact('lessons'));
What this is doing:
compact() essentially takes the object/variable by it's name ($lessons) and passes it to the view with the same name.
An alternative way is to write it as:
...
return view('admin.lessons.index')->with('lessons', $lessons);
Cheers!
The reason you're getting the error in your server but not your local machine is that your server database is empty (or at least has fewer records).
{{$lesson->subject->subject}}
The lesson has no subject, so it's null. And your tryting to get a proprty subject of a null.
If you're using Laravel 5.5, you can wrap the subject in optional() method.
{{optional($lesson->subject)->subject}}
< Laravel 5.5
{{$lesson->subject ? $lesson->subject->subject : ''}}

laravel display only specific column from relation

I have read a few topics about this, but they managed to solve my problem partially ...
this is my controller
class DeskController extends BaseController{
public function getDeskUsers($deskId){
$user = DeskUserList::where(function($query) use ($deskId){
$query->where('deskId', $deskId);
})->with('userName')->get(array('deskId'));
if (!$user->isEmpty())
return $user;
return 'fail';
}
this is the model
class DeskUserList extends Eloquent {
protected $table = 'desk_user_lists';
public function userName(){
return $this->belongsTo('User', 'userId')->select(array('id','userName'));
}
}
the method getDeskUsers may returns ALL the DeskUserList table records, related with the User table record (on deskUserList.userId = User.id).
practically I want each record returned is composed of:
DeskUserList.deskId
User.userName
eg. [{"deskId":"1","user_name":antonio}]
What i get is
[{"deskId":"1","user_name":null}]
As you can see the user name is a null value...
BUT
if I edit my controller code:
->with('userName')->get(array('userId')); //using userId rather than deskId
then i get
[{"userId":"2","user_name":{"id":"2","userName":"antonio"}}]
By this way I still have two problem:
the userId field is twice repeated
I miss the deskId field (that I need...)
hope be clear, thanks for your time!
You need belongsToMany, no need for a model representing that pivot table.
I assume your models are Desk and User:
// Desk model
public function users()
{
return $this->belongsToMany('User', 'desk_user_list', 'deskId', 'userId');
}
// User model
public function desks()
{
return $this->belongsToMany('Desk', 'desk_user_list', 'userId', 'deskId');
}
Then:
$desks = Desk::with('users')->get(); // collection of desks with related users
foreach ($desks as $desk)
{
$desk->users; // collection of users for particular desk
}
// or for single desk with id 5
$desk = Desk::with('users')->find(5);
$desk->users; // collection of users
$desk->users->first(); // single User model

Resources