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

yugsoni2103's avatar

Looping in laravel

I am working on a review management system in which I am getting user id in the database from which I have to retrieve the data of the user like the name which will be shown in the view. For example if we have 10 comments added in the database with their publisher's user id we will have to get their name and show them simultaneously before the review.

I am using foreach loop in which every review is shown but how can I display the publishers name on the review block. For example: - -> Publish date -> Publisher's Name -> Review

So here I am not able to show the publisher's name, I have tried doing it with foreach but it display all the names in that column where as I have to show a particular name of one publisher by the id which has been entered in the database while writing the review

0 likes
4 replies
jlrdw's avatar

I suggest taking the free learning laravel in 30 days course. You'll learn basic relations from which you can build from.

1 like
Randy_Johnson's avatar

Give me the model names, as well as the data what you have for each model. Then I can give you your solution.

Here is an attempt:

Tables: User, Publisher, Review

Tables

// User

id, name, email, password

// Publisher

id, user_id, forename, surname

// Review

id, publisher_id, review

Relationships

// User

public function publisher() {
		return $this->hasOne(Publisher::class);
}

// Publisher

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

public function reviews() {
		return $this->hasMany(Review::class);
}

// Review

public function review() {
		return $this->belongsTo(Review::class);
}
1 like
yugsoni2103's avatar

It's fine I managed to do it, I have checked the validation through if else conditions and got my desired results

Please or to participate in this conversation.