John Davidson

php - How to get a single row by id in my laravel 8 project

0 comments
Message:


i'm new to laravel and trying to show a single row using its (id) in my view.blade.php, right now it works, but when i select another license_id it only shows' the contents of the first row (id) since they have same foriegn key, and the funny thing is that the route shows that am in the license_id i selected.


public function viewlicense($id)
{
if(Beat::where('id', $id)->exists())
{
if(License::where('beat_id', $id)->exists())
{
$licenses = License::where('beat_id', $id)->first();
return view('frontend.licenses.view', compact('licenses'));
}
else{
return redirect('/')->with('Status', "The link was broken");
}
}
else{
return redirect('/')->with('Status', "No such beat found");
}
}




Route::get('/', [FrontendController::class, 'index']);
Route::get('beat', [FrontendController::class, 'beat']);
Route::get('view-beat/{id}', [FrontendController::class, 'viewbeat']);
Route::get('view-beat/{beat_slug}/{license_slug}', [FrontendController::class, 'viewlicense']);

Edited Code


public function beat()
{
$beats = Beat::all();
return view('frontend.beat', compact('beats'));
}

public function viewbeat($slug)
{
if(Beat::where('slug', $slug)->exists())
{
$beat = Beat::where('slug', $slug)->first();
$licenses = License::where('beat_id', $beat->id)->get();
return view('frontend.licenses.index', compact('beat', 'licenses'));
}
else{
return redirect('/')->with('Status', "id doesnot exists");
}
}

public function viewlicense($beat_slug, $license_slug)
{
if(Beat::where('slug', $beat_slug)->exists())
{
if(License::where('slug', $license_slug)->exists())
{
$licenses = License::where('slug', $license_slug)->first();
return view('frontend.licenses.view', compact('licenses'));
}
else{
return redirect('/')->with('Status', "The link was broken");
}
}
else{
return redirect('/')->with('Status', "No such beat found");
}
}


My Answer:
In your updated code, you are passing both the beat_slug and license_slug to the viewlicense function. This allows you to uniquely identify the license you want to display based on both the beat and license slugs.

Make sure that the slug fields in your Beat and License models are unique and properly set up.

Also, in your viewlicense function, you are querying the License model based on the slug instead of the beat_id. This ensures that you are fetching the correct license based on the unique slug.

If you are still experiencing issues with displaying the correct license, double-check your database to ensure that the slugs are unique and correctly associated with the respective beats and licenses.

Rate this post

5 of 5 based on 8121 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us