TheCodingKid
TheCodingKid

Reputation: 115

Display data in laravel using one to many relationship

I'm trying to display data using laravel. I currently want to display reviews of the hotels on my system. Prior to modifications of code my posts were showing, however with the following code, no posts show at all and i am struggling as to why this is happening.

PostsController.php

public function show($id)
{
    $post = Post::find($id);
    $review = Post::find(1)->reviews()->where('title', 'posts_title')->get();

    return view('posts.show', compact('post', 'review'));
}

Post.php

public function reviews()
{
    return $this->hasMany('App\Review', 'title', 'post_title');
}

Review.php

public function post()
{    
    return $this->belongsTo('App\Post');
}

the variable title is the title of the review. post_title is the title of the hotel. Both titles should match (in my system they do). I know you would use ID's but i think that is difficult in my situation

I want to display the review that matches the right hotel. Bare in mind previously, all my hotels were displaying, however after changing the code it does not display

Upvotes: 0

Views: 123

Answers (1)

Kenny Horna
Kenny Horna

Reputation: 14241

The reason you are getting no Reviews in your query is this line:

$review = Post::find(1)->reviews()->where('title', 'posts_title')->get();
//                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

When you use a where() clause the first parameter is the column name to query against and the second parameter is the actual value to compare.. not a column name. So this will try to find every review that has a title with a value "posts_title" (literally)... hence you have 0 records returned.

Now, you also need to know how relationships work. If you define a relationship in your Post model like the following:

# Post.php

public function reviews()
{
    return $this->hasMany('App\Review', 'title', 'post_title');
}

This will work as follows: It'll get all the reviews that has the reviews.title column equals to posts.post_title column.

So, if this setup is correct for your dabatase, you won't need to re-state this condition, just execute the query and call the relationship method instead:

# PostsController.php

$related_reviews = Post::find(1)->reviews;

Also notice that, in need of use the reverse relationship, you'll need to also tell laravel the custom PK/FK to use in order to get the correct results.

# Review.php

public function post()
{
    return $this->belongsTo('App\Post', 'title', 'post_title');
}

As a side note, if you manage your hotels as posts in your database.. a proper name for this model and table should be Hotel and hotels, respectively.

Upvotes: 2

Related Questions