use relationship in model accessor in laravel
Suppose I have a Course model like this :
class Course extends Model
{
public $primaryKey = 'course_id';
protected $appends = ['teacher_name'];
public function getTeacherNameAttribute ()
{
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
}
public function teacher ()
{
return $this->belongsTo('AppUser', 'teacher', 'user_id');
}
}
And in the other hand there is a User model like this :
class User extends Authenticatable
{
public $primaryKey = 'user_id';
protected $appends = ['full_name'];
public function getFullNameAttribute ()
{
return $this->name . ' ' . $this->family;
}
public function course ()
{
return $this->hasMany('AppCourse', 'teacher', 'user_id');
}
}
As you can see there is a hasMany relationship between those.
There is an full_name accessor in User model.
Now I want to add a teacher_name accessor to Course model that uses it's teacher relations and gets full_name of teacher and appends to Course always.
In fact I want whenever call a Course model, it's related teacher name included like other properties.
But every time , when call a Course model , I got this error :
exception 'ErrorException' with message 'Trying to get property of non-object' in D:wampwwwlms-apiappCourse.php:166
That refers to this line of Course model :
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
I do not know how can I solve that and what is problem exactly.
php laravel laravel-5.4
add a comment |
Suppose I have a Course model like this :
class Course extends Model
{
public $primaryKey = 'course_id';
protected $appends = ['teacher_name'];
public function getTeacherNameAttribute ()
{
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
}
public function teacher ()
{
return $this->belongsTo('AppUser', 'teacher', 'user_id');
}
}
And in the other hand there is a User model like this :
class User extends Authenticatable
{
public $primaryKey = 'user_id';
protected $appends = ['full_name'];
public function getFullNameAttribute ()
{
return $this->name . ' ' . $this->family;
}
public function course ()
{
return $this->hasMany('AppCourse', 'teacher', 'user_id');
}
}
As you can see there is a hasMany relationship between those.
There is an full_name accessor in User model.
Now I want to add a teacher_name accessor to Course model that uses it's teacher relations and gets full_name of teacher and appends to Course always.
In fact I want whenever call a Course model, it's related teacher name included like other properties.
But every time , when call a Course model , I got this error :
exception 'ErrorException' with message 'Trying to get property of non-object' in D:wampwwwlms-apiappCourse.php:166
That refers to this line of Course model :
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
I do not know how can I solve that and what is problem exactly.
php laravel laravel-5.4
$this->teacher()->first(), i wonder, does it require->first()or not.
– Bagus Tesa
May 9 '17 at 6:41
It doesn't.$this->teacher->full_namewill do the trick.
– Angelin Calu
May 9 '17 at 6:42
add a comment |
Suppose I have a Course model like this :
class Course extends Model
{
public $primaryKey = 'course_id';
protected $appends = ['teacher_name'];
public function getTeacherNameAttribute ()
{
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
}
public function teacher ()
{
return $this->belongsTo('AppUser', 'teacher', 'user_id');
}
}
And in the other hand there is a User model like this :
class User extends Authenticatable
{
public $primaryKey = 'user_id';
protected $appends = ['full_name'];
public function getFullNameAttribute ()
{
return $this->name . ' ' . $this->family;
}
public function course ()
{
return $this->hasMany('AppCourse', 'teacher', 'user_id');
}
}
As you can see there is a hasMany relationship between those.
There is an full_name accessor in User model.
Now I want to add a teacher_name accessor to Course model that uses it's teacher relations and gets full_name of teacher and appends to Course always.
In fact I want whenever call a Course model, it's related teacher name included like other properties.
But every time , when call a Course model , I got this error :
exception 'ErrorException' with message 'Trying to get property of non-object' in D:wampwwwlms-apiappCourse.php:166
That refers to this line of Course model :
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
I do not know how can I solve that and what is problem exactly.
php laravel laravel-5.4
Suppose I have a Course model like this :
class Course extends Model
{
public $primaryKey = 'course_id';
protected $appends = ['teacher_name'];
public function getTeacherNameAttribute ()
{
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
}
public function teacher ()
{
return $this->belongsTo('AppUser', 'teacher', 'user_id');
}
}
And in the other hand there is a User model like this :
class User extends Authenticatable
{
public $primaryKey = 'user_id';
protected $appends = ['full_name'];
public function getFullNameAttribute ()
{
return $this->name . ' ' . $this->family;
}
public function course ()
{
return $this->hasMany('AppCourse', 'teacher', 'user_id');
}
}
As you can see there is a hasMany relationship between those.
There is an full_name accessor in User model.
Now I want to add a teacher_name accessor to Course model that uses it's teacher relations and gets full_name of teacher and appends to Course always.
In fact I want whenever call a Course model, it's related teacher name included like other properties.
But every time , when call a Course model , I got this error :
exception 'ErrorException' with message 'Trying to get property of non-object' in D:wampwwwlms-apiappCourse.php:166
That refers to this line of Course model :
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
I do not know how can I solve that and what is problem exactly.
php laravel laravel-5.4
php laravel laravel-5.4
edited Jun 18 at 3:23
Jeff Puckett
14k651102
14k651102
asked May 9 '17 at 6:28
A.B.Developer
2,45333783
2,45333783
$this->teacher()->first(), i wonder, does it require->first()or not.
– Bagus Tesa
May 9 '17 at 6:41
It doesn't.$this->teacher->full_namewill do the trick.
– Angelin Calu
May 9 '17 at 6:42
add a comment |
$this->teacher()->first(), i wonder, does it require->first()or not.
– Bagus Tesa
May 9 '17 at 6:41
It doesn't.$this->teacher->full_namewill do the trick.
– Angelin Calu
May 9 '17 at 6:42
$this->teacher()->first(), i wonder, does it require ->first() or not.– Bagus Tesa
May 9 '17 at 6:41
$this->teacher()->first(), i wonder, does it require ->first() or not.– Bagus Tesa
May 9 '17 at 6:41
It doesn't.
$this->teacher->full_name will do the trick.– Angelin Calu
May 9 '17 at 6:42
It doesn't.
$this->teacher->full_name will do the trick.– Angelin Calu
May 9 '17 at 6:42
add a comment |
3 Answers
3
active
oldest
votes
the right way to do this is:
COURSE
public function setTeacherNameAttribute ()
{
$this->attributes['teacher_name'] = $this->teacher->full_name;
}
really? whyset....Attribute?
– A.B.Developer
May 9 '17 at 6:53
because you are defining the value of the attribute .. not fetching .. if your fetching then just doreturn $this->teacher->full_name;
– Demonyowh
May 9 '17 at 6:57
add a comment |
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
Should be
$this->attributes['teacher_name'] = $this->teacher->full_name;
First thing is that you want to reference the relationship, so loose the brackets (), and because the relationship is belongsTo, you will have one user / teacher returned. So you don't need the first().
We haven't seen your fields but probably you will have to change:
return $this->belongsTo('AppUser', 'teacher', 'user_id');
to
return $this->belongsTo('AppUser', 'foreign_key', 'other_key');
where foreign_key and other_key are the primary keys that you need to make the join on.
Check this link from the documentation for reference:
https://laravel.com/docs/5.4/eloquent-relationships#one-to-many-inverse
I tried your solution. but when calling a course model, that return this :{ "course": { "teacher_name": null, "course_teacher": null } }
– A.B.Developer
May 9 '17 at 6:58
That could only mean two things. Either there is no definedteacherfor thecourse. Or the relationship definition is wrong.
– Angelin Calu
May 9 '17 at 7:28
I sure thatforeign_keyandother_keyis correct but I do not know why that returnsnull
– A.B.Developer
May 9 '17 at 8:28
add a comment |
This error is only object data to array use or array data to object data use.
example::
$var->feild insted of $var[feild]
$var[feild] insted of $var->feild
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43862597%2fuse-relationship-in-model-accessor-in-laravel%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
the right way to do this is:
COURSE
public function setTeacherNameAttribute ()
{
$this->attributes['teacher_name'] = $this->teacher->full_name;
}
really? whyset....Attribute?
– A.B.Developer
May 9 '17 at 6:53
because you are defining the value of the attribute .. not fetching .. if your fetching then just doreturn $this->teacher->full_name;
– Demonyowh
May 9 '17 at 6:57
add a comment |
the right way to do this is:
COURSE
public function setTeacherNameAttribute ()
{
$this->attributes['teacher_name'] = $this->teacher->full_name;
}
really? whyset....Attribute?
– A.B.Developer
May 9 '17 at 6:53
because you are defining the value of the attribute .. not fetching .. if your fetching then just doreturn $this->teacher->full_name;
– Demonyowh
May 9 '17 at 6:57
add a comment |
the right way to do this is:
COURSE
public function setTeacherNameAttribute ()
{
$this->attributes['teacher_name'] = $this->teacher->full_name;
}
the right way to do this is:
COURSE
public function setTeacherNameAttribute ()
{
$this->attributes['teacher_name'] = $this->teacher->full_name;
}
answered May 9 '17 at 6:48
Demonyowh
1,3411613
1,3411613
really? whyset....Attribute?
– A.B.Developer
May 9 '17 at 6:53
because you are defining the value of the attribute .. not fetching .. if your fetching then just doreturn $this->teacher->full_name;
– Demonyowh
May 9 '17 at 6:57
add a comment |
really? whyset....Attribute?
– A.B.Developer
May 9 '17 at 6:53
because you are defining the value of the attribute .. not fetching .. if your fetching then just doreturn $this->teacher->full_name;
– Demonyowh
May 9 '17 at 6:57
really? why
set....Attribute?– A.B.Developer
May 9 '17 at 6:53
really? why
set....Attribute?– A.B.Developer
May 9 '17 at 6:53
because you are defining the value of the attribute .. not fetching .. if your fetching then just do
return $this->teacher->full_name;– Demonyowh
May 9 '17 at 6:57
because you are defining the value of the attribute .. not fetching .. if your fetching then just do
return $this->teacher->full_name;– Demonyowh
May 9 '17 at 6:57
add a comment |
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
Should be
$this->attributes['teacher_name'] = $this->teacher->full_name;
First thing is that you want to reference the relationship, so loose the brackets (), and because the relationship is belongsTo, you will have one user / teacher returned. So you don't need the first().
We haven't seen your fields but probably you will have to change:
return $this->belongsTo('AppUser', 'teacher', 'user_id');
to
return $this->belongsTo('AppUser', 'foreign_key', 'other_key');
where foreign_key and other_key are the primary keys that you need to make the join on.
Check this link from the documentation for reference:
https://laravel.com/docs/5.4/eloquent-relationships#one-to-many-inverse
I tried your solution. but when calling a course model, that return this :{ "course": { "teacher_name": null, "course_teacher": null } }
– A.B.Developer
May 9 '17 at 6:58
That could only mean two things. Either there is no definedteacherfor thecourse. Or the relationship definition is wrong.
– Angelin Calu
May 9 '17 at 7:28
I sure thatforeign_keyandother_keyis correct but I do not know why that returnsnull
– A.B.Developer
May 9 '17 at 8:28
add a comment |
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
Should be
$this->attributes['teacher_name'] = $this->teacher->full_name;
First thing is that you want to reference the relationship, so loose the brackets (), and because the relationship is belongsTo, you will have one user / teacher returned. So you don't need the first().
We haven't seen your fields but probably you will have to change:
return $this->belongsTo('AppUser', 'teacher', 'user_id');
to
return $this->belongsTo('AppUser', 'foreign_key', 'other_key');
where foreign_key and other_key are the primary keys that you need to make the join on.
Check this link from the documentation for reference:
https://laravel.com/docs/5.4/eloquent-relationships#one-to-many-inverse
I tried your solution. but when calling a course model, that return this :{ "course": { "teacher_name": null, "course_teacher": null } }
– A.B.Developer
May 9 '17 at 6:58
That could only mean two things. Either there is no definedteacherfor thecourse. Or the relationship definition is wrong.
– Angelin Calu
May 9 '17 at 7:28
I sure thatforeign_keyandother_keyis correct but I do not know why that returnsnull
– A.B.Developer
May 9 '17 at 8:28
add a comment |
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
Should be
$this->attributes['teacher_name'] = $this->teacher->full_name;
First thing is that you want to reference the relationship, so loose the brackets (), and because the relationship is belongsTo, you will have one user / teacher returned. So you don't need the first().
We haven't seen your fields but probably you will have to change:
return $this->belongsTo('AppUser', 'teacher', 'user_id');
to
return $this->belongsTo('AppUser', 'foreign_key', 'other_key');
where foreign_key and other_key are the primary keys that you need to make the join on.
Check this link from the documentation for reference:
https://laravel.com/docs/5.4/eloquent-relationships#one-to-many-inverse
$this->attributes['teacher_name'] = $this->teacher()->first()->full_name;
Should be
$this->attributes['teacher_name'] = $this->teacher->full_name;
First thing is that you want to reference the relationship, so loose the brackets (), and because the relationship is belongsTo, you will have one user / teacher returned. So you don't need the first().
We haven't seen your fields but probably you will have to change:
return $this->belongsTo('AppUser', 'teacher', 'user_id');
to
return $this->belongsTo('AppUser', 'foreign_key', 'other_key');
where foreign_key and other_key are the primary keys that you need to make the join on.
Check this link from the documentation for reference:
https://laravel.com/docs/5.4/eloquent-relationships#one-to-many-inverse
edited May 9 '17 at 7:33
answered May 9 '17 at 6:45
Angelin Calu
6182926
6182926
I tried your solution. but when calling a course model, that return this :{ "course": { "teacher_name": null, "course_teacher": null } }
– A.B.Developer
May 9 '17 at 6:58
That could only mean two things. Either there is no definedteacherfor thecourse. Or the relationship definition is wrong.
– Angelin Calu
May 9 '17 at 7:28
I sure thatforeign_keyandother_keyis correct but I do not know why that returnsnull
– A.B.Developer
May 9 '17 at 8:28
add a comment |
I tried your solution. but when calling a course model, that return this :{ "course": { "teacher_name": null, "course_teacher": null } }
– A.B.Developer
May 9 '17 at 6:58
That could only mean two things. Either there is no definedteacherfor thecourse. Or the relationship definition is wrong.
– Angelin Calu
May 9 '17 at 7:28
I sure thatforeign_keyandother_keyis correct but I do not know why that returnsnull
– A.B.Developer
May 9 '17 at 8:28
I tried your solution. but when calling a course model, that return this :
{ "course": { "teacher_name": null, "course_teacher": null } }– A.B.Developer
May 9 '17 at 6:58
I tried your solution. but when calling a course model, that return this :
{ "course": { "teacher_name": null, "course_teacher": null } }– A.B.Developer
May 9 '17 at 6:58
That could only mean two things. Either there is no defined
teacher for the course. Or the relationship definition is wrong.– Angelin Calu
May 9 '17 at 7:28
That could only mean two things. Either there is no defined
teacher for the course. Or the relationship definition is wrong.– Angelin Calu
May 9 '17 at 7:28
I sure that
foreign_key and other_key is correct but I do not know why that returns null– A.B.Developer
May 9 '17 at 8:28
I sure that
foreign_key and other_key is correct but I do not know why that returns null– A.B.Developer
May 9 '17 at 8:28
add a comment |
This error is only object data to array use or array data to object data use.
example::
$var->feild insted of $var[feild]
$var[feild] insted of $var->feild
add a comment |
This error is only object data to array use or array data to object data use.
example::
$var->feild insted of $var[feild]
$var[feild] insted of $var->feild
add a comment |
This error is only object data to array use or array data to object data use.
example::
$var->feild insted of $var[feild]
$var[feild] insted of $var->feild
This error is only object data to array use or array data to object data use.
example::
$var->feild insted of $var[feild]
$var[feild] insted of $var->feild
edited Nov 13 at 7:05
answered Jun 18 at 3:28
Kiran Kanzar
707
707
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43862597%2fuse-relationship-in-model-accessor-in-laravel%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$this->teacher()->first(), i wonder, does it require->first()or not.– Bagus Tesa
May 9 '17 at 6:41
It doesn't.
$this->teacher->full_namewill do the trick.– Angelin Calu
May 9 '17 at 6:42