1

I have just got this error all the tries while updating my table data.

ErrorException: Creating default object from empty value

AdminController.php

public function update(Request $r, $post_id) {
    $post = Post::find($post_id);

    $post->post_title = $r->post_title;
    $post->post_image = $r->post_image;
    $post->post_details = $r->post_details;
    $post->post_rating = $r->post_rating;
    $post->id = $r->id;
    
    $post->save();

    return back();
}

My Resource Route

Route::resource('post', AdminController::class);

Blade File

<div class="edit-post-content">

    <form action="{{ route('post.update',$list->post_id) }}" method="POST">
        @csrf
        @method('PUT')

        <input type="hidden" name="id" value="{{$list->id}}">
        <input type="hidden" name="post_rating" value="{{$list->post_rating}}">
        <div class="mb-3">
            Edit Title: <input class="form-control" name="post_title" type="text" id="exampleFormControlInput1" value="{{$list->post_title}}" aria-label="default input example">
        </div>
        <div class="mb-3">
            Edit Description:
            <textarea class="form-control" id="exampleFormControlTextarea1"  name="post_details"  rows="3">
                {{ $list->post_details }}
            </textarea>
        </div>
        <div>
            <img src="{{asset('images/'.trim($list->post_image))}}" alt="" width="120px;">
            Edit Photos:
            <input id="formFileMultiple" class="form-control form-control-lg" name="post_image" type="file" value="{{ $list->post_image }}" multiple>
        </div>
        <button type="submit" class="btn btn-primary">Save Changes</button>
    </form>

</div>

Could someone help me, please?

1
  • 2
    Welcome to SO ... find can return null, you need to check for that before using what is returned from find as an object Commented Aug 17, 2021 at 2:08

1 Answer 1

1

There is a chance that the model doesn't exist. You can add a check for this in your controller as follows:

public function update(Request $r, $post_id) {
    $post = Post::find($post_id);
    if (!$post) {
        // You can add code to handle the case when the model isn't found like displaying an error message
        return back();
    }

    $post->post_title = $r->post_title;
    $post->post_image = $r->post_image;
    $post->post_details = $r->post_details;
    $post->post_rating = $r->post_rating;
    $post->id = $r->id;
    
    $post->save();

    return back();
}
Sign up to request clarification or add additional context in comments.

1 Comment

yes thats right....... Model not found in update scenario. But i deleted the same table by this model. How can i resolve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.