Есть возможность добавить теги в статьи. Между статьями и тегами существует множество отношений. У меня есть article_tag Table.
Код: Выделить всё
class Tag extends Model
{
use HasFactory;
protected $fillable = ['name'];
public function articles()
{
return $this->belongsToMany(Article::class);
}
}
Код: Выделить всё
public function tags()
{
return $this->belongsToMany(Tag::class)->as('tags');
}
< /code>
I Контроллер ArticleController У меня есть два метода для редактирования и обновления статьи: < /p>
public function edit($id)
{
$article = Article::find($id);
$attached_tags = $article->tags()->get()->pluck('id')->toArray();
return view(
'dashboard/edit-article',
[
'categories' => $this->categories(),
'tags' => $this->tags(),
'attached_tags' => $attached_tags,
'article' => $article
]
);
}
public function update(Request $request, $id)
{
$validator = Validator::make($request->all(), $this->rules, $this->messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors())->withInput();
}
$fields = $validator->validated();
$article = Article::find($id);
// If a new image is uploaded, set it as the article image
// Otherwise, set the old image...
if (isset($request->image)) {
$imageName = md5(time()) . Auth::user()->id . '.' . $request->image->extension();
$request->image->move(public_path('images/articles'), $imageName);
} else {
$imageName = $article->image;
}
$article->title = $request->get('title');
$article->short_description = $request->get('short_description');
$article->category_id = $request->get('category_id');
$article->tags[] = $request->get('tags[]');
$article->featured = $request->has('featured');
$article->image = $request->get('image') == 'default.jpg' ? 'default.jpg' : $imageName;
$article->content = $request->get('content');
// Save changes to the article
$article->save();
//Attach tags to article
if (isset($request->tags)) {
$article->tags()->sync($request->tags);
} else {
$article->tags()->sync([]);
}
return redirect()->route('dashboard.articles')->with('success', 'The article titled "' . $article->title . '" was updated');
}
Код: Выделить всё
{{ __('Tags') }}
@foreach ($tags as $tag)
id, $attached_tags) ? 'selected' : '' }}>{{ $tag->name }}
@endforeach
Где моя ошибка?
Подробнее здесь: https://stackoverflow.com/questions/794 ... -invalid-f
Мобильная версия