目前,当我想在帖子中添加标签时,我必须转到我的tags page
并创建它们然后转到我的post create
页面并通过多个输入字段将它们添加到我的帖子中一切都很好。
但是,如果我想让我的标签系统像WordPress一样工作怎么办?表示我在post create page
的多个字段中编写我的代码,如果该代码已经存在则会添加,如果不是,那么新代码将是save in database
,也会在该帖子中添加?
Laravel版本:5.5
更新
PostController
注意:我的帖子根据我的应用需要命名食物(只是命名不同)
创建方法
public function create()
{
$ingredients = Ingredient::all();
$vaghts = Vaght::all();
$categories = Category::all();
$user = Auth::user();
return view('panel.foods.create', compact('ingredients', 'vaghts', 'user','categories'));
}
存储方法
public function store(Request $request)
{
//Validating title and body field
$this->validate($request, array(
'title'=>'required|max:225',
'slug' =>'required|max:255',
'user_id' =>'required|numeric',
'image' =>'sometimes|image',
'description' => 'required|max:100000',
'category_id' => 'required|numeric',
'status' => 'required|numeric',
));
$food = new Food;
$food->title = $request->input('title');
$food->slug = $request->input('slug');
$food->user_id = $request->input('user_id');
$food->description = $request->input('description');
$food->category_id = $request->input('category_id');
$food->status = $request->input('status');
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'food' . '-' . time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/');
$request->file('image')->move($location, $filename);
$food->image = $filename;
}
$food->save();
$food->vaghts()->sync($request->vaghts, false);
$food->ingredients()->sync($request->ingredients, false);
//Display a successful message upon save
Session::flash('flash_message', 'Food, '. $food->title.' created');
return redirect()->route('foods.index');
}
标签方法:注意:我有两种不同类型的标签,它们是相同的,所以如果我只能得到一个,我会自己做下一个标签
创建方法
public function create()
{
return view('panel.vaghts.create');
}
存储方法
public function store(Request $request)
{
//Validating title and body field
$this->validate($request, array(
'title'=>'required|max:225',
));
$vaght = new Vaght;
$vaght->title = $request->input('title');
$vaght->save();
//Display a successful message upon save
Session::flash('flash_message', 'Timing, '. $vaght->title.' created');
return redirect()->route('timing.index');
}
答案 0 :(得分:0)
答案 1 :(得分:0)
您可以先尝试搜索哪些标记已存在,哪些标记是新标记,然后创建新标记。之后,附加/同步从用户收到的所有标签。
//get old vaghts title
$existingVaghts = $food->vaghts->pluck('title')->toArray();
//find new vaghts
foreach($request->vaghts as $vaght) {
if(! ( in_array($vaght, $existingVaghts) ) ) {
//create a new vaght
$newVaght = new App\Vaght;
$newVaght->title = $vaght;
$newVaght->save();
}
}
$attachableVaghts = [];
foreach($request->vaghts as $vaght) {
$attachableVaghts[] = App\Vaght::where('title', $vaght)->pluck('id')->first();
}
$food->vaghts()->sync($attachableVaghts);
我认为应该这样做。希望能帮助到你。 请查看以下链接以获取更多https://codeshare.io/5Ppygd
另外,对于刀片模板,请检查以下链接 https://codeshare.io/axeN7R