我试图插入一个annn,但它给了我错误Array to string conversion
。我知道所有字段都不是强制性的,因为插入是根据刀片edit
中选择的subcategory_id完成的
AnnancesController.php
public function store(Request $request)
{
$request->validate([
'category_id'=>['bail','required',],
'souscategory_id'=>['bail','required',],
'entreprise' =>['bail','exclude_unless:souscategory_id,1','required','string','min:2','max:255'],
'domaine' =>['bail','exclude_unless:souscategory_id,1','required','string'],
'contrat' =>['bail','exclude_unless:souscategory_id,1','required','string',],
'niveaua' =>['bail','exclude_unless:souscategory_id,1','required','string'],
'poste' =>['bail','exclude_unless:souscategory_id,2','required','string'],
'marquem' =>['bail','exclude_unless:souscategory_id,7','required','string'],
'marque' =>['bail','exclude_unless:souscategory_id,8','required','string'],
'modele' =>['bail','exclude_unless:souscategory_id,8','required','string'],
'annee' =>['bail','exclude_unless:souscategory_id,8','required','string'],
'km' =>['bail','exclude_unless:souscategory_id,8','required','numeric'],
'carburant' =>['bail','exclude_unless:souscategory_id,8','required','string','min:2','max:255'],
'puissance' =>['bail','exclude_unless:souscategory_id,8','required','string','min:2','max:255'],
'titre' =>['bail','exclude_unless:souscategory_id,1','required','string','min:2','max:255'],
'description' =>['bail','exclude_unless:souscategory_id,1','required','string','min:30','max:255'],
'prix' =>['bail','exclude_unless:souscategory_id,6','required','min:1','max:12'],
'image' =>['bail','exclude_unless:souscategory_id,1','required','mimes:jpeg,jpg,png,gif,svg','max:2048'],
'images.*' =>['bail','exclude_unless:souscategory_id,1','required','mimes:jpeg,jpg,png,gif,svg','max:2048'],
//2 emploi/
]);
if($request->hasFile('image'))
{
$path = $request->image->store('annonces');
$request->image = $path;
}
$request->user_id = Auth::user()->id;
$Annonce = new Annonce($request->all());
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
要在Laravel中从$request
创建一个新元素,您需要按照以下步骤进行,并将$request
的每个值分配给Announce
对象的每个属性:
$request->user_id = Auth::user()->id;
$Annonce = new Annonce();
$Annonce->user_id = $request->user_id;
$Annonce->some_column = $request->some_column;
$Account->save();
您可以通过以下方式尝试:
use AppModelsAnnounce;
............................
$data = $request->all();
if ($request->hasFile('image')) {
$path = $request->image->store('annonces');
$data['image'] = $path;
}
$data['user_id'] = Auth::user()->id;
Announce::create($data);
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
请确保在应用程序上导入了正确的模型命名空间
虽然不建议修改请求,但您应该这样做:
$request->request->add(['image' => $path, 'user_id' => Auth::user()->id]);
或通过
$request = array_merge($request->all(), ['image' => $path, 'user_id' => Auth::user()->id]));