【问题标题】:ERROR: Trying to get property id error in Laravel (non object)错误:试图在 Laravel 中获取属性 ID 错误(非对象)
【发布时间】:2021-07-30 20:17:43
【问题描述】:

你能描述一下我的代码有什么问题吗?当我单击更新按钮并获取更新请求的 ID 时,它们是错误的。我想要做的是用帖子更新类别名称和标签(post_tag 即属于多) 它说“试图获得非对象的属性。

//类 Post 扩展模型

public function category()
{
    return $this->belongsTo('App\Category');
}

public function tags()
{
    return $this->belongsToMany('App\Tag');
}

// 类标签扩展模型

    public function posts()
{
    return $this->belongsToMany('App\Post');
}

// 类类别扩展模型

protected $table = 'categories';

public function posts()
{
    return $this->hasMany('App\Post');
}

// 后控制器

public function edit($id)
{
    // find the post in the database and save as a var
    $post = Post::find($id);

    $categories = Category::with('posts')->get();
    $cats = array();
    foreach ($categories as $category) {
        $cats[$category->id] = $category->name;
    }

    $tags = Tag::with('posts')->get();
    $tags2 = array();
    foreach ($tags as $tag) {
        $tags2[$tag->id] = $tag->name;
    }
    // return the view and pass in the var we previously created
    return view('backend.pages.posts.edit')->withPost($post)->withCategories($cats)->withTags($tags2);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    // Validate the data
    $post = Post::find($id);

    if ($request->input('slug') == $post->slug) {
        $this->validate($request, array(
            'title' => 'required|max:255',
            'category_id' => 'required|integer',
            'body'  => 'required'
        ));
    } else {
    $this->validate($request, array(
            'title' => 'required|max:255',
            'slug'  => 'required|alpha_dash|min:5|max:255|unique:posts,slug',
            'category_id' => 'required|integer',
            'body'  => 'required'
        ));
    }

    // Save the data to the database
    $post = Post::find($id)->first();

    $post->title = $request->input('title');
    $post->slug = $request->input('slug');
    $post->category_id = $request->input('category_id');
    $post->body = $request->input('body');

   
    if (isset($request->tags)) {
        $post->tags()->sync($request->tags);
    } else {
        $post->tags()->sync(array());
    }
    $post->save();
    notify()->success("The blog post was successfully updated!", 'Success');

     return redirect()->route('app.posts.show', $post->id);
    // return back();

}

//edit.blade.php 文件

//select 选项找到一个非对象的 id 时出现错误

// 下面的 2 行代码位于表单 POST METHOD {{ route('app.posts.update', $post->id) }} //

<select class="form-control" name="category_id" class="form-control @error('category_id') is-invalid @enderror" required>
@foreach($categories as $key=>$category)
    <option value="{{ $category>id }}" @isset($post) {{ $post->category->id == $category->id ? 'selected' : '' }} @endisset>{{ $category->name}}</option>
@endforeach
// 标签名称下面的相同错误无法获取属性
<select class="form-control select2-multi" id="tags" name="tags[]" multiple>
        @foreach($tags as $key=>$tag)
            <option value="{{ $tag }}" {{ old('tags[]', $post->tag)->contains($tag) ? 'selected' : '' }}>{{ $tag->name }}</option>
        @endforeach
</select>

//结束表格

【问题讨论】:

  • 您在哪个代码行收到错误?你能评论一下你的代码吗?
  • 当我尝试更新选择类别时,此代码发生错误。

标签: mysql laravel eloquent laravel-7


【解决方案1】:

我明白了。 $categories 传递给视图的变量是一个数组,键是类别 ID,值是类别名称。在您看来,在循环内部,$category 变量是一个字符串,但您尝试将其作为对象 ($category-&gt;id) 访问并得到错误。

解决方案 1:

您可以像这样更新您的代码:

<select class="form-control" name="category_id" class="form-control @error('category_id') is-invalid @enderror" required>
@foreach($categories as $categoryId => $categoryName)
    <option value="{{ $categoryId }}" @isset($post) {{ $post->category->id == $categoryId ? 'selected' : '' }} @endisset>{{$categoryName}}</option>
@endforeach

<select class="form-control select2-multi" id="tags" name="tags[]" multiple>
    @foreach($tags as $tagId => $tagName)
        <option value="{{ $tagId }}" {{ old('tags[]', $post->tags)->contains($tagId) ? 'selected' : '' }}>{{ $tagName }}</option>
    @endforeach
</select>

解决方案 2:

我看到在控制器操作中,您将类别和标签转换为数组,这不是必需的。只需从数据库中获取它们并传递给视图。

public function edit($id)
{
    // find the post in the database and save as a var
    $post = Post::find($id);

    $categories = Category::with('posts')->get();


    $tags = Tag::with('posts')->get();

    return view('backend.pages.posts.edit', [
        'post' => $post,
        'categories' => $categories,
        'tags' => $tags,
    ]);
    // Or you can even write: return view('backend.pages.posts.edit', compact('post', 'categories', 'tags'));
}

那么在你看来:

<select class="form-control" name="category_id" class="form-control @error('category_id') is-invalid @enderror" required>
@foreach($categories as $category)
    <option value="{{ $category->id }}" @isset($post) {{ $post->category->id == $category->id ? 'selected' : '' }} @endisset>{{$category->name}}</option>
@endforeach

<select class="form-control select2-multi" id="tags" name="tags[]" multiple>
    @foreach($tags as $tag)
        <option value="{{ $tag->id }}" {{ old('tags[]', $post->tags)->contains($tag->id) ? 'selected' : '' }}>{{ $tag->name }}</option>
    @endforeach
</select>

【讨论】:

  • 当我点击按钮页面加载并且什么都没有发生...我认为它来自我的 POST 方法...有什么想法吗?
  • 我已经更新了我的答案。您的意思是提交表单吗?
  • 是的,完全正确...页面继续加载,但没有任何反应。
  • 您想在控制器操作中记录一些数据以进行调试:laravel.com/docs/8.x/logging#introduction
  • 谢谢...我在 slug 验证错误中得到了它。感谢您的记录!
猜你喜欢
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 2016-06-13
  • 2018-06-02
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多