Home > Software engineering >  Pass data from view to Bootstrap 5 modal in Laravel 9
Pass data from view to Bootstrap 5 modal in Laravel 9

Time:10-26

I'm using Bootstrap 5 modal to do CU out of CRUD operations. I would like to pass data from different models into my Add/Update modal.

So this is how I open my editModal and pass data to it right now:

@foreach ($categories as $category)
   <button type="button"  data-bs-toggle="modal" data-bs-target="#editModal{{$category->id}}">
      Edit
   </button>
   @include("manage/categories/editModal")
@endforeach

Inside of editModal file:

<div  id="editModal{{$category->id}}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">

    <form action="{{ route('manage/categories/edit', ['id' => $category->id]) }}" method="POST">
        @csrf
    <div >
        <div >
            <div >
            </div>
            <div >
                <label for="category name">Name</label>
                <input type="text" name="name" id="{{$category->id}}"  placeholder="" value="{{$category->name}}">
            </div>
            <div >
                <button type="button"  data-bs-dismiss="modal">Close</button>
                <button type="submit" >Add</button>
            </div>
        </div>
    </div>
   </form>
</div>

and it works all gucci, as long as I'm using only 1 data Model(category)

But there is the case that I need to pass also every Size model item. That's why I'm returning sizes inside of my index view(in controller):

public function index()
    {
        $sizes = Size::get();
        $categories = Category::get();

        return view('/manage/products/index',['categories' => $categories],['sizes' => $sizes]);
    }

But for some point, update or add modals still only seee categories model and throws error on sizes loop:

@foreach($sizes as $size)
   option value="{{ $size->id }}">{{ $size->name }}</option>
@endforeach

enter image description here

What might be solution optimal solution according to my case?

Thanks in advance.

Btw. What do You think about this solution to pass data into modal :)?

CodePudding user response:

You need to pass all parameters to the view as a single array, like this:

return view('/manage/products/index',['categories' => $categories, 'sizes' => $sizes]);
  • Related