Nested Selected Value Laravel

  eloquent, html, laravel, php

I’m trying to get the selected value to return the correct item but I think the foreach is messing it up, I can’t thing of a way to get around it.

My View

    <div class="images">
    @foreach($images as $image)
    <div class="images-container">
        <form method="POST" action="{{route('gallery.destroy', $image->id)}}">
            @csrf
            @method("DELETE")
            <button onclick="return confirm('Are you sure?')" type="submit"><i class="fas fa-trash"></i></button>
        </form>
        <img src="{{asset('storage/images/' . $image->fail_path)}}" alt="imagenonoshow">
        <form method="POST" action="{{url('admin/gallery/update/' . $image->categoryRel->first()->id)}}">
            <select name="category">
                @foreach($category as $item)
                <option selected="{{$image->categoryRel->first()->title}}">{{$item->title}}</option>
                @endforeach
            </select>
        </form>
    </div>
    @endforeach
</div>

My Model

class File extends Model {
use HasFactory;

protected $fillable = [
    'name',
    'file_path',
    'category_id'
];

public function categoryRel()
{
    return $this->hasMany(Category::class, 'id', 'category_id');
}

}

The index of my controller

class fileUploadController extends Controller{
public function index()
{

    $images = File::with('categoryRel')->get();
    $category = Category::orderBy('id', 'asc')->get();

    return view('admin.gallery.index', compact('images', 'category'));

}

Source: Ask PHP

LEAVE A COMMENT