Undefined variable when returning view as HTML via AJAX

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:


public function store(Request $request)
            'name' => 'required'

        $category = new Category();
        $category->name = $request->name;

        $returnHTML = view('categories.new', compact($category))->render();
        return response()->json(array(
            'success' => true, 
            'html' => $returnHTML,
            'icon' => 'success',
            'title' => 'Added',
            'msg' => 'Category successfully added.'


$('#category-submit').click( function() {
        var name = $('#name').val();
        let _url = '/categories';
        let _token = $('meta[name="csrf-token"]').attr('content');

            url: _url,
            type: 'POST',
            data: {
                name: name,
                _token: _token
            success: function(data) {



                    title: data.title,
                    text: data.msg,
                    icon: data.icon,
                    showConfirmButton: false,
                    timer: 1500
            error: function(xhr) {


<tr id="category-{{ $category->id }}">
    <td>{{ $category->name }}</td>
        <button class="btn btn-inverse-primary btn-icon-text">
            <i class="ti-pencil btn-icon-prepend"></i> Edit
        <button data-id="{{ $category->id }}" class="category-delete btn btn-inverse-danger btn-icon-text">
            <i class="ti-trash btn-icon-prepend"></i> Delete

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.


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

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x