【问题标题】:ErrorException: Creating default object from empty value - LaravelErrorException:从空值创建默认对象 - Laravel
【发布时间】:2021-08-17 12:29:56
【问题描述】:

我在更新我的表格数据时所有尝试都遇到了这个错误。

ErrorException: 从空值创建默认对象

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();
}

我的资源路线

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

刀片文件

<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>

有人可以帮帮我吗?

【问题讨论】:

  • Welcome to SO ... find 可以返回 null,您需要在使用从 find 返回的内容作为对象之前检查这一点

标签: php laravel


【解决方案1】:

model 有可能不存在。您可以在控制器中为此添加检查,如下所示:

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();
}

【讨论】:

  • 是的,没错.......在更新场景中找不到模型。但是我用这个模型删除了同一张表。我该如何解决这个问题?
猜你喜欢
  • 2016-08-18
  • 1970-01-01
  • 2018-04-27
  • 2017-11-29
  • 2018-07-18
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多