ERROR: Trying to get property id error in Laravel (non object)

ERROR: Trying to get property id error in Laravel (non object)

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

//class Post 扩展模型

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

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

// class 标签扩展模型

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

// class 类别扩展模型

protected $table = 'categories';

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

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

// 下面的两行代码位于表单 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
// tag name 下面同样的错误无法获取 属性
<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>

//结束形式

我明白了。您传递给视图的 $categories 变量是一个数组,键是类别 ID,值是类别名称。在您看来,在循环内,$category 变量是一个字符串,但您尝试将其作为对象 ($category->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>