So I'm very new to laravel, and I want to know the best way on how to do the following: So I have on the main page couple of villas with their information such as Title and address (all information is from the table in the database) and the goal is when I click on its name I want it to route me to a view blade that has all its information such as images, address, description(all its values in database), and when I click on the other villa also give its own information.
maybe depending on each unique id? but with one route?
please some help!
CodePudding user response:
Well, I hope this gives you fair idea and a starting point
In the route file
//Your route for the individual villas
Route::get('/villa/{id}', function (id) {
$myvilla = Villa::find(id);
return view('villa.profile', ['villa' => $myvilla]);
});
Route::get('/villas', function(){
$myvillas = Villa::all();
return view('user.profile', ['villas' => $myvillas]);
});
In the view where all the villas are displayed, do display the ids in the link
<ul>
@foreach ($villas as $villa)
<li><a href="URL::to('/villa/'.$villa->id)">{{ $villa->name }} </li>
@endforeach
</ul>
Note for security reasons use uuid for your ids for this approach. I exempted the Controller bit so you need to use controllers to add more features as well.
CodePudding user response:
web.php:
Route::get('/villas/{villa}', function (Villa $villa) {
return view('villas.details', compact('villa'));
})->name('villas-details');
Route::get('/villas', function(){
$villas = Villa::all();
return view('villas.overview', compact('villas'));
})->name('villas-overview');
villas.blade.php
<ul>
@foreach ($villas as $villa)
<li><a href="{{ route('villas-details', compact('villa') }}">{{ $villa->name }}</li>
@endforeach
</ul>
CodePudding user response:
wrap each villas with a href tag as below and send the id.
<a href="{{route('villas.details',$villa->id)}}" >Villa 1</a>
i generally use tables so my code is something like this.
@foreach($villas as $villa)
<tr>
<td>
<a href="{{route('villas.details',$villa->id)}}" >
{{$villa->name}}
</a>
</td>
<td>
other column(s)
</td>
</tr>
@endforeach
the route for this should be as follows
Route::get('details/{id}', [
'as' => 'villas.details',
'uses' => 'VillaController@getDetails',
]);
public function getDetails($id)
{
$villaDetails= Villa::find($id);
return view('villas.detail-info', compact('villaDetails'));
}
In the detail-info blade do what ever you like with the villaDetails.
A bit of advice if you are new always use dump and dd to check the data. :)