【发布时间】: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