I’m new to Laravel and I’m trying to prepend the view when adding a new category. I’m always getting the error:
Undefined variable: category (View: ..new.blade.php) … Line 1
Here’s what I have so far:
CategoryController.php
public function store(Request $request) { $request->validate([ 'name' => 'required' ]); $category = new Category(); $category->name = $request->name; $category->save(); $returnHTML = view('categories.new', compact($category))->render(); return response()->json(array( 'success' => true, 'html' => $returnHTML, 'icon' => 'success', 'title' => 'Added', 'msg' => 'Category successfully added.' )); }
script.blade.php
$('#category-submit').click( function() { var name = $('#name').val(); let _url = '/categories'; let _token = $('meta[name="csrf-token"]').attr('content'); $.ajax({ url: _url, type: 'POST', data: { name: name, _token: _token }, success: function(data) { $('tbody').prepend(data.html); $('#name').val(''); $('#category-modal').modal('hide'); Swal.fire({ title: data.title, text: data.msg, icon: data.icon, showConfirmButton: false, timer: 1500 }); }, error: function(xhr) { console.log(xhr.responseText); } }); });
new.blade.php
<tr id="category-{{ $category->id }}"> <td>{{ $category->name }}</td> <td> <button class="btn btn-inverse-primary btn-icon-text"> <i class="ti-pencil btn-icon-prepend"></i> Edit </button> <button data-id="{{ $category->id }}" class="category-delete btn btn-inverse-danger btn-icon-text"> <i class="ti-trash btn-icon-prepend"></i> Delete </button> </td> </tr>
I honestly don’t know what I’m doing wrong. It seems $category
from controller won’t be passed to new.blade.php
. Any help would be greatly appreciated.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
As described here in php doc, you should pass the name of the variable as a string in compact()
method.
$returnHTML = view('categories.new', compact('category'))->render();
Or you can pass the variable to blade file using array.
$returnHTML = view('categories.new', ['category' => $category])->render();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0