I'am trying to make a featured photo for my product images. I have successfully made radio buttons with the product images id associated to them. When I click on a radio button and submit it, it sets a "featured" column in the product_images table to 1 ( or True). The problem I'm having is I only want 1 photo to be featured for each product. When I go choose and click a different image to be featured, it inserts it into the database with a 1 also.
How can I make it so there is only 1 featured image per product. So if some other image is selected, make all other images default back to 0 (or False) with that product_id.
Here is my form:
<form method="post" action="/store/admin/products/add/featured/{{ $products->id }}">
{!! csrf_field() !!}
@foreach($products->photos as $set)
<label>{{ $set->id }} </label>
<input type="radio" name="featured" value="{{ $set->id }}" {{ $set->featured === 1 ? "checked=checked" : "" }}>
@endforeach
<button type="submit" class="btn btn-primary waves-effect waves-light">Feature Image</button>
</form>
My function to insert featured image in DB:
public function storeFeaturedPhoto($id, Request $request) {
// Check if radio button is checked or not for featured image
$featured = Input::has('featured') ? true : false;
// Validate featured button
$this->validate($request, [
'featured' => 'required'
]);
// Grab the ID of the Image being featured from radio button
$featured2 = Input::get('featured');
// Select All from product_images where the photo ID is the photo id being selected from radio button
$image = ProductPhoto::where('id', '=', $featured2);
// Select from product_images wherew featured = 1 and the product ID = to the product id in the URL, then count the results
$count = ProductPhoto::where('featured', '=', 1)->where('product_id', '=', $id)->count();
if ($count > 1) {
// Do something here to deselect all other images with this product_id??????????
}
// update the product_photos table with the featured photo
$image->update([
'featured' => $featured,
]);
// Return redirect back
return redirect()->back();
}