0

How do I get the data from a relationship table?

this is the tables' structure:

paradises
    id - integer
    title - string
    travel_interest_id - integer
 
travel_interests
    id - integer
    name - string

and this is my code so far

Models/Paradise.php

    public function travelInterests()
    {
        return $this->belongsTo(TravelInterest::class);
    }

Models/TravelInterest.php

    public function paradises()
    {
        return $this->hasMany(Paradise::class);
    }

in this Controller, I'm getting all the data from the travel_interests table instead of just one record that is associated with the paradise record.

ParadiseController.php

public function show(Paradise $paradise)
{
    dd($paradise->travelInterests->get());
}

what am I doing wrong? any help is appreciated..

1

1 Answer 1

0

$paradise->travelInterests is a relationship method on your model, you should call it as a method with parentheses.

$paradise->travelInterests()->get();
Sign up to request clarification or add additional context in comments.

2 Comments

$paradise->travelInterests is preferred!
@OMiShah $paradise->travelInterests is preferred if you want to work directly with the relationship without explicitly calling get(). When you access travelInterests as a property, Eloquent automatically handles fetching the related data for you, making it more convenient and cleaner. $paradise = Paradise::with('travelInterests')->get(); this one is best to avoid N+1 query problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.