Laravel get data based on relationship

Viewed 89

So i have two tables, Bids table and Projects table. Relationship between them as such:

Bids.php:

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

Projects.php:

public function bids()
{
    return $this->hasMany('App\Bids');
}

This is Projects table. This is Bids table. I want to print all the bid data along with their respective projects data in each row of table in View. I tried to do this way in my controller:

$bids= auth()->user()->bids()->get();
   foreach($bids as $bid)
   {
        $projects= Projects::find($bid->project_id);
   }
    return view('bids.index',compact('bids','projects'));

index view:

 @if($bids->count() != 0)
           @foreach($bids as $bid)                      
            <tr>
            <td><a href="{{ route('projects.select',$projects->id) }}">{{$projects->name}}</a></td>
             <td>{{$bid->status}}</td>
             </tr> 
             @endforeach
                                
             @else
             <tr>
             <td colspan="6" class="text-center">No record found.</td>
             </tr>
             @endif

But I got the data repeated in one row of table. So what should be the proper way to do it? Sorry if this is a bit vague, but this is my best way to explain it in abstract.

1 Answers

You are not using the relationship you defined here.

$bids = auth()->user()->bids()->with('project')->get();

This will eager load the project relationship for each Bid.

I really don't know how you want this to look in the view but you can iterate the bids and get the project information pretty simply:

@foreach ($bids as $bid)
    {{ $bid->id }}
    {{ $bid->project->name ?? '' }}
@endforeach

Side note:

Your Projects model should be Project, models are named in the singular and the database tables are named in the plural. Your relationship should be project not projects since it is a singular relationship, belongs to; it can only return a single record or null.

Related