Laravel - Eloquent return only one value - php

How can I return one value from a belongsToMany relation.
This is my relation:
public function role() {
return $this->belongsToMany('App\Role');
}
Now when I want to access the Role Name I have to do the folowing:
Auth::user()->role[0]->name
But I just want to do
Auth::user()->role
But now my question is: "How can I do that?"

to do this you need add custom attribute to user model as the following:
User Model:
protected $appends = ['role']; // add new attribute to user model
public function getRoleAttribute()
{
return $this->roles->first(); // don't use roles() it would execute every time
}
public function roles() {
return $this->belongsToMany('App\Role');
}
now you can use
Auth::user()->role

Auth::user()->role()->first()
Besides the question itself, i suggest you to use the plural name for belogsToMany relations: it is a common best practice and makes the code much more expressive.
public function roles() {
return $this->belongsToMany('App\Role');
}
Auth::user()->roles()->first()

Related

How to define custom user id for relationship

I have a Laravel 9 forum project and for the Question Model, I added this:
public function user()
{
return $this->belongsTo(User::class);
}
And for User Model, I added this:
public function questions()
{
return $this->hasMany(Question::class);
}
Basically, every question has a field named creator_id and I want to connect the relationship between these two Models based on this field.
So how can I do that?
This part of the documentation shows you how to set those relationships. It suggest doing the following:
Question model
public function user()
{
return $this->belongsTo(User::class, 'creator_id');
}
User model
public function questions()
{
return $this->hasMany(Question::class, 'creator_id');
}

why laravel 6 many-to-many relationship does not working?

Hi I simply want to get permissions of the role, I am trying following
$r = Role::find(1);
dd($r->permissions);
The above script does not return any permission however you can see there is data in the below tables. I also tried following but no luck
$role = Role::with('permissions')->where('id', 1)->first();
I have data in the table as you can see
Table:tes_permissions
Table: tes_roles
Table: tes_permission_role
And following are Models
class Permission extends Model
{
protected $table = 'tes_permissions'
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
And
class Role extends Model
{
protected $table = 'tes_roles';
public function permissions() {
return $this->belongsToMany('App\Permission', 'tes_permission_role', 'permission_id', 'role_id');
}
}
Can someone kindly guide me what can be the issue, I would appreciate.
You mixed the order of properties in the belongsToMany(). The third argument is specifying the ID for the model defining the relationship. So change to the following:
public function permissions() {
return $this->belongsToMany('App\Permission', 'tes_permission_role', 'role_id', 'permission_id');
}
And on the Permission model, also define it to be sure.
public function roles()
{
return $this->belongsToMany('App\Role', 'tes_permission_role', 'permission_id', 'role_id');
}

Laravel Eloquent elation for pivot table

I'm currently working on a laravel project, but I'm kind of stuck finding the right eloquent relations.
My tables and the connections (should) look like this:
Project Relations
My model relations look like this:
User
public function team()
{
return $this->hasMany(Team::class, 'user_id');
}
public function evaluation()
{
return $this->hasMany(Evaluation::class, 'user_id');
}
Team
public function user()
{
return $this->belongsTo(User::class);
}
public function survey()
{
return $this->hasMany(Survey::class, 'team_id');
}
Evaluation
public function user()
{
return $this->belongsTo(User::class);
}
public function survey()
{
return $this->hasMany(Survey::class, 'evaluation_id');
}
Survey
public function team()
{
return $this->belongsTo(Team::class);
}
public function evaluation()
{
return $this->belongsTo(Evaluation::class);
}
public function surveyresponse()
{
return $this->hasMany(SurveyResponse::class, 'survey_id');
}
SurveyResponse
public function survey()
{
return $this->belongsTo(Survey::class);
}
public function testquestion()
{
return $this->belongsTo('App\TestQuestion');
}
Is this the way to go? Do I need a "Has Many Through" relation here? Or a "Polymorphic Relationship"?
Seems correct to me, i just didnt see the TesteQuestion model (your last relation).
Answering your question:
The HasManyThrough relation is just a shortcut for accessing distant relations via an intermediate relation, in your case: Users has many evaluations that has many surveys. With this relationship you could get all surveys from a user.
Your relation would look like this:
/**
* Get all of the surveys for the user.
*/
public function surveys()
{
return $this->hasManyThrough('App\Survey', 'App\Evaluation');
}
You can access this relation like this:
$user->surveys();
But you can achieve the same (without using the HasManyThrough) by doing:
$user->evaluations()->surveys();
Beware that this will return the evaluations too, not just the surveys and it requires more processing.
So i recommend you doing the HasManyThrough relationship if you pretend to access the surveys a lot.

Using a polymorphic relation in a child model causes an infinite loop?

This question was already asked here but it received no answer. Now I face the same problem but in laravel 5.4. I have a model Book, a model ReadingSession and a model Comment. A book has many reading sessions and has many comments but the reading session can also have comments. So I have my relations defined like this:
Book.php
protected $with = [
'author',
'readingSessions',
'userRating',
'ratings',
'comments'
];
public function users()
{
return $this->belongsToMany(User::class, 'user_book');
}
public function author()
{
return $this->belongsTo(Author::class);
}
public function allReadingSessions()
{
return $this->hasMany(ReadingSession::class);
}
public function readingSessions()
{
return $this->hasMany(ReadingSession::class)
->where('user_id', Auth::user()->id);
}
public function ratings()
{
return $this->hasMany(Rating::class);
}
public function userRating()
{
return $this->hasMany(Rating::class)
->where('user_id', Auth::user()->id);
}
public function comments()
{
return $this->morphMany('App\Models\Comment', 'commentable');
}
ReadingSession.php
protected $with = ['comments'];
public function user()
{
return $this->belongsTo(User::class);
}
public function book()
{
return $this->belongsTo(Book::class);
}
public function comments()
{
return $this->morphMany('App\Models\Comment', 'commentable');
}
Comment.php
public function commentable()
{
return $this->morphTo();
}
These seems to create an infinite loop. Can anyone hint me on what I'm doing wrong?
The main reason you might have an infinite loop there is if you are trying to load automatically a relationship that in turn tries to do the same with the previous model.
Putting it into an example:
Book.php
protected $with = [
'author',
];
public function author()
{
return $this->belongsTo(Author::class);
}
Author.php
protected $with = [
'books',
];
public function books()
{
return $this->hasMany(Book::class);
}
In this case, every time you fetch an author it will fetch automatically his books that in turn will try to fetch the author and on and on...
One other thing that might happen and it's harder to realize is when using the $appends property on some accessors. If you are trying automatically had a variable into a model through the $appends and if that accessor fetches a relation or uses a relation in some way you might get an infinite loop again.
Example:
Author.php
protected $appends = [
'AllBooks',
];
public function books()
{
return $this->hasMany(Book::class);
}
public function getAllBooksAttribute() {
return $this->books->something...
}
In this case, every time the app tries to resolve your Author model it will fetch the books, that in turn will fetch the Author, that in turn will fetch the books again and on and on...
From your snippets, is not clear what is causing the problem but this answer might give some leads where to search for it.
To solve it, you might remove the relation from the $with and load it manually: $author->load('books') or Author::with('books')->where...
You can also load a relation of a relation in this way, for example: $author->load('books', 'books.comments') or Author::with('books', 'books.comments')->where...
It all comes down what you are trying to achieve. So you have to evaluate what and what not you should auto-load.
Be careful when loading automatically relations on your models and when adding accessors to $appends, especially if they use relations. It is an awesome feature but can bite hard sometimes.

Laravel 4:: Returning models and its relationship

I would like to return the model and part of its relationship
EX::
User model
public function comments()
{
return $this->hasMany('comments');
}
Comments model
public function user()
{
return $this->belongsTo('user');
}
Can I return all comments and the user's name associated with the comment?
The desired effect is
$comment = Comments::find($id);
$comment->user;
return $comment;
This will return the one comment and the associated user full model. I just need the name of the user. And this does not works if I call Comments::all()
Thank you in advance.
You're looking for Eloquent's Eager Loading
Assuming your Comments model has a method user():
public function user()
{
return $this->belongsTo('User');
}
You should be able to do this in your controller:
$comments = Comments::with('user')->where('post_id', $post_id);
// Return JSON, as is Laravel's convention when returning
// Eloquent model directly
return $comments;
You can do the opposite as well:
Assuming your User model has a method 'comments()', like so:
public function comments()
{
return $this->hasMany('Comment');
}
Inside of your controller, you should be able to do the following, assuming your have the $id of the user available:
$user = User::with('comments')->find($id);
// Return JSON, as is Laravel's convention when returning
// Eloquent model directly
return $user;

Categories