Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

princeoo7's avatar

Need Eloquent Relationship help.

Hello Every one. I am new to eloquent relationship and i am sucked with following questions.

i have three tables.

  1. article.
  2. gallery.
  3. user.
  • article table have a column creator ( user_id ). same goes for gallery.
  • an article can have gallery with many pics uploaded by different users.
  • user table is firstname, lastname, username, email id, contact number etc.

Q 1 ) now i was trying to fetch creator with belongsTo(USER::CLASS); which gives me data, but the function name which i want to keep as creator only returns the user_id from article table. How can i just get the username in place of user_id ?

Q 2 ) by using hasOne(GALLERY::CLASS) i can get the gallery records for that article but how can i get username user who uploaded the images from the record of gallery as per article.

Q 3 ) if i user print_r or return json of the article record, i am only able to get the article record. but if i use article::find(1)->gallery; then i will get gallery record for that record. how can i get print all the data at once at the time of development like what we get in yii2 ?

Q 4) also i am facing below error on using print_f on the object. The Response content must be a string or object implementing __toString(), "boolean" given.

Q 5) how can i get username of the moderator who as updated the profile of the creator of a article. i.e. $article->creator->profile->moderator or $article->creator->profile->moderator->username

thank you for going through my thread. I hope i was able to represent my doubt properly.

0 likes
10 replies
tykus's avatar
tykus
Best Answer
Level 104

One

If the column is creator, then the relationship should have a different name (this is why we tend to have the _id suffix). I would suggest using creator_id as the column name, and creator as the relationship name - it stays close to convention:

// Article.php

public function creator()
{
    return $this->belongsTo(User::class); // creator_id is inferred from the relationship name
}

Two If you have a hasOne relationship, then you should be getting zero or one Gallery instances, not galleries. Notwithstanding, you can traverse the relationship once they have been correctly setup. An Article hasOne Gallery; a Gallery belongsTo a creator (User), so that same suggestion applies as before for the column name on galleries table

// Gallery.php
public function creator()
{
    return $this->belongsTo(User::class); // creator_id is inferred from the relationship name
}

Then, whenever you have an Article instance, you can traverse the relationships (so long as gallery and creator will return an object!

$article->gallery->creator->name;

Three Don't know yii, but you can eager-load the relations so they are nested in the parent object:

$article = Article::with('gallery')->find(1);

// or use dot syntax to eager-load nested relations
$article = Article::with('gallery.creator')->find(1);

// or multiple relations:
$article = Article::with(['creator', 'gallery.creator')->find(1);

Four Without seeing the code that generates the response. it is impossible to assist

Five So long as the relationships exist, and the records are associated, then $article->creator->profile->moderator->username will work, but that is a long chain; it might be better to find a way to simplify the call.

2 likes
princeoo7's avatar

while i was waiting for the reply, i was able to get to the point of eager load relation ship.

now i am only stuck with two things,

  1. getting only gallery image where record column "is_banner" = 1;

  2. getting username of the user who has updated the article creator's profile.

ArticleController.php 

class PropertyController extends Controller
{
    public function index()
        {     
            $records = Article::paginate(10);
            $records->map(function ($data) {
                return $data->creator->profile;
     });
    
        return view('pages.artilce.index', ['records' => $records]);
        }
 }          

Article.php

public function creator() { return $this->belongsTo(User::class, 'created_by'); }

    public function moderator() { return $this->belongsTo(User::class, 'updated_by'); }

    public function attachments() { return $this->hasMany(Gallery::class); }

princeoo7's avatar

@tykus your answer was very much at points i needed to get by. can you help with the above code ? currently i am using below code in my index.blade.php

i would like to do this via vuejs in future. what can i do to just get the image which is banner image ? or whats the best way to handle this situation... thank you for your assistance.

@foreach($record->gallery as $img)
    @if($img->is_banner)
        @if(strpos($img->url, 'http') === 0)
            <img class="card-img-top" src="<?=$img->url?>" alt="Card image">
        else
            <img class="card-img-top" src="/<?=$img->url?>" alt="Card image">
        @endif
    @endif
@endforeach

tykus's avatar

getting only gallery image where record column "is_banner" = 1;

You could create another relationship specifically for the banner image:

// Article.php
public function banner()
{
    return $this->hasOne(Gallery::class)->where("is_banner", 1);
}

This means $article->banner will return a single Gallery (image) instance.

This could also be achieved using a join, or a sub select.

getting username of the user who has updated the article creator's profile.

What is the relationship between User and moderator?

princeoo7's avatar

@tykus moderator now called as updated_by have the user_id.

Profile.php 
class Profile extends Model
{

        public function moderator()
        {
            return $this->belongsTo(User::class);
        }
}

tykus's avatar

You need to tell Eloquent which column to use for the relationship because the column name does not match the relation name:

public function moderator()
{
    return $this->belongsTo(User::class, 'updated_by');
}
1 like
princeoo7's avatar

@tykus as you suggested, i used the where clause and got the is_banner record. but how do i access it ?

my out put is as followed.

if i use in index.blade.php,

{{$record->banner}}



[{"id":1,"property_id":1,"is_banner":1,"url":"https:\/\/placehold.it\/1024x768","original_filename":null,"description":"Et aliquam reiciendis eos voluptatem et explicabo in. Assumenda quidem architecto voluptatibus neque.","status":1,"creator":505,"updated_by":505,"created_at":"2019-02-21 14:26:31","updated_at":"2019-02-21 14:26:31","deleted_at":null}] 

{{$record->banner-url}}

Property [url] does not exist on this collection instance. (View: C:\xampp\htdocs\db\resources\views\pages\article\index.blade.php)

{{$record->banner['url']}}  

Undefined index: url (View: C:\xampp\htdocs\db\resources\views\pages\article\index.blade.php)

Article.php
public function banner() 
{
    return $this->hasMany(Gallery::class)->where("is_banner", 1);
}   

tykus's avatar

hasOne per my previous post, not hasMany

public function banner() 
{
    return $this->hasOne(Gallery::class)->where("is_banner", 1);
}  

Then

$article->banner->url
princeoo7's avatar

@tykus thank you so much for your help. really appreciate it. and i think i should go to sleep now. i just missed such a simple thing :/

1 like

Please or to participate in this conversation.