may I need specific method to print vehicle and photos data on each project_id?
how to display table data in laravel 5.6
Hi, in My laravel 5.6 application I have 3 tables with models called as projects,vehicles,photos. Projects table have many to many relationship with vehicles and photos tables and they have belongsTo relationship with projects table. vehicles and photos table have project_id as foreign key. Project model
public function vehicles()
{
return $this->hasMany(Vehicle::class);
}
public function photos()
{
return $this->hasMany(Photo::class);
}
Vehicle model
public function project()
{
return $this->belongsTo(Project::class);
}
Photo model
public function project()
{
return $this->belongsTo(Project::class);
}
vehicles table contains some vehicles informations witch related to project and photos table is contain images of project. I have index.blade.php file to print project data as following,
projects/index.blade.php
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
@if($projects)
@foreach($projects as $project)
{{$project->district}}
{{$project->town}}
{{$project->brand}}
{{$project->model}}
{{$project->year}}
{{$project->condition}}
{{$project->detail}}
{{$project->price}}
{{$project->telephone}}
{{$project->email}}
{{$project->name}}
<hr>
@endforeach
@endif
</div>
</div>
</div>
@endsection
I have following Controllers, ProjectController
public function index()
{
$projects = Project::all();
return view('projects.index')->withProjects($projects);
}
VehicleController
public function index()
{
$vehicles = Vehicle::all();
return view('vechicles.index')->withVehicles($vehicles);
}
PhotosController
public function index()
{
$photos = Upload::all();
return view('photos.index', compact('photos'));
}
now I need print vehicle information and photos witch related to each project_id in the vehicles and photos table in to this blade file(projects/index.blade.php). how can do this?
eager load the relations
public function index()
{
$projects = Project::with('vehicles','photos')->all();
return view('projects.index')->withProjects($projects);
}
In the view you can then iterate over the relations
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
@if($projects)
@foreach($projects as $project)
{{$project->district}}
{{$project->town}}
{{$project->brand}}
{{$project->model}}
{{$project->year}}
{{$project->condition}}
{{$project->detail}}
{{$project->price}}
{{$project->telephone}}
{{$project->email}}
{{$project->name}}
<hr>
@foreach($project->vehicles as $vehicle)
// get stuff about each vehicle
{{ $vehicle->something }}
@endforeach
@foreach($project->photos as $photo)
// get stuff about each photo
{{ $photo->something }}
@endforeach
@endforeach
@endif
</div>
</div>
</div>
@endsection
Please or to participate in this conversation.