Search code examples
laravelbootstrap-modalbootstrap-5laravel-9

Pass data from view to Bootstrap 5 modal in Laravel 9


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" class="btn btn-warning edit" data-bs-toggle="modal" data-bs-target="#editModal{{$category->id}}">
      Edit
   </button>
   @include("manage/categories/editModal")
@endforeach

Inside of editModal file:

<div class="modal fade" 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 class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
            </div>
            <div class="modal-body">
                <label for="category name">Name</label>
                <input type="text" name="name" id="{{$category->id}}" class="form-control" placeholder="" value="{{$category->name}}">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">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 :)?


Solution

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

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