banda
banda

Reputation: 402

How to fix Undefined variable: image in Laravel 5.6

I'm working with Laravel 5.6 and in my application I have a category create form in the form.blade.php file...

@if(isset($image))
    <form method="PUT" action="http://localhost:8000/update" enctype="multipart/form-data">
    <input type="hidden" name="_method" value="put">
@else
   <form method="POST" action="http://localhost:8000/create" accept-charset="UTF-8" enctype="multipart/form-data"><input name="_token" type="hidden" value="1LLYc0D1spmVSFMboLDjGM9MR4O5APVwng7giejx">
                                {{csrf_field()}}
@endif

            <div class="form-group row required">
                <label for="description" class="col-form-label col-md-3 col-lg-2">Description</label>
                <div class="col-md-8">
                    <input class="form-control" autofocus placeholder="Description" name="description" type="text" id="description" value="{{$image->categoryname}}">
                </div> 
            </div>

I have both new category create form and edit form in the above blade file.

this is my CategoryController

public function edit($id)
{
    $images = Category::find($id);

    return view('categories.form')->withImages($images);
}

My edit form is working fine but when I click new Category create button it is generating following error

Undefined variable: image (View: C:\Users\Nalaka\Desktop\acxian\resources\views\categories\form.blade.php)

Upvotes: 1

Views: 3255

Answers (1)

Nikola Gavric
Nikola Gavric

Reputation: 3543

Im not sure I've seen this method withImage inside of Laravel, I would suggest you try with just with, like this:

public function edit($id)
{
    $image = Category::find($id);

    return view('categories.form')->with(['image' => $image]);
}

If that doesn't work, then you need to include if statement for the image description too, because you have {{ $image->categoryname }} and you are not checking for it's existence at that point

EDIT: To envelop this into an if else statement, you can use ternary operator for it, like this:

{{ isset($image) ? $image->categoryname : '' }}

Upvotes: 3

Related Questions