cinameng
cinameng

Reputation: 323

how to access properties from Laravel collections within foreach

I have a Laravel collection with relations returned to a view and I need to access it's properties;

controller

$project = Project::with('pulls.builds')->where('id',$id)->get();

view

@foreach ($project as $project->pulls) 
 {{ $project->pulls }}    
@endforeach 

output

{"id":2,"created_at":null,"updated_at":null,"name":"Project Name","pulls":[{"id":2,"created_at":null,"updated_at":null,"branch":".fixes","project_id":2,"builds":[{"id":3,"created_at":null,"updated_at":null,"description":"43662-4768-456","pull_id":2}]},{"id":3,"created_at":null,"updated_at":null,"branch":".test","project_id":2,"builds":[{"id":4,"created_at":null,"updated_at":null,"description":"build 1","pull_id":3}]}]}

I have all the data that I want, now I need to make it look like this when viewed by the user:

Project Name

.fixes
43662-4768-456

.test
build 1

Upvotes: 0

Views: 44

Answers (1)

IGP
IGP

Reputation: 15786

$projects = Project::with('pulls.builds')->where('id',$id)->get();

Given the structure of the json, to echo out every property you'd need to do something like this

@foreach($projects as $project)
  {{ $project->id }}
  {{ $project->created_at }}
  {{ $project->updated_at }}
  {{ $project->name }}
  @foreach($project->pulls as $pull)
    {{ $pull->id }}
    {{ $pull->created_at }}
    {{ $pull->updated_at }}
    {{ $pull->branch }}
    {{ $pull->project_id }}
    @foreach($pull->builds as $build)
      {{ $build->id }}
      {{ $build->created_at }}
      {{ $build->updated_at }}
      {{ $build->description }}
      {{ $build->pull_id }}
    @endforeach
  @endforeach
@endforeach

So taking only what you need, and adding some html, it could end up looking like this:

<p>Projects:</p>
@foreach($projects as $project)
  <p>Project Name: <span>{{ $project->name }}</span></p>
  <p>Pulls:</p>
  @foreach($project->pulls as $pull)
    <p>Branch: <span>{{ $pull->branch }}</span></p>
    <p>Builds:</p>
    @foreach($pull->builds as $build)
      <p>Description: <span>{{ $build->description }}</span></p>
    @endforeach
  @endforeach
@endforeach

If you only want a single project, instead of using ->where('id', $id)->get(), use ->find($id) and you can remove the first @foreach.

Upvotes: 1

Related Questions