我目前是 laravel 的新手,我正在从事一个基本项目,服务提供商 (SP) 可以通过填写表格来发布服务详细信息。
我正在尝试检查 SP 是否已上传精选图片。如果是,则使用重命名文件
$featured = $request->featured;
$featured_new_name = time().$featured->getClientOriginalName();
$featured->move('uploads/services', $featured_new_name);
并将其保存到uploads/services/
目录中。
我的ServiceController.php
长相是这样的
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'address' => 'required|max:255',
'city' => 'required|max:255',
'state' => 'required|max:255',
'zipcode' => 'required|integer|digits:5',
'category_id' => 'required',
'workingday' => 'required',
'content' => 'required'
]);
//checking if featured image (logo file) is uploaded or not
if($request->hasfile('featured'))
{
$featured = $request->featured;
$featured_new_name = time().$featured->getClientOriginalName();
$featured->move('uploads/services', $featured_new_name);
}
else { }
$featured->move('uploads/services', $featured_new_name);
$service = Service::create([
'name' => $request->name,
'content' => $request->content,
'address' => $request->address,
'city' => $request->city,
'state' => $request->state,
'zipcode' => $request->zipcode,
]);
if($request->hasfile('featured'))
{
$service = Service::create([
'name' => $request->name,
'content' => $request->content,
'featured' =>'uploads/services/'.$featured_new_name,
'address' => $request->address,
'city' => $request->city,
'state' => $request->state,
'zipcode' => $request->zipcode,
]);
}
$service->workingdays()->attach($request->workingday);
$service->categories()->attach($request->category_id);
$service->user_id=auth()->id();
$service->save();
Session::flash('success','Service created successfully');
return view('sp.services.create')->with('categories', Category::all())->with('workingday', Workingday::all());
}
在迁移文件中:
public function up()
{
Schema::create('services', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('address');
$table->string('city');
$table->string('state');
$table->string('zipcode');
$table->integer('routes_id');
$table->string('featured')->default('/uploads/services/default.png');
$table->text('content')->nullable();
$table->string('slug');
$table->integer('user_id');
$table->softDeletes();
$table->timestamps();
});
}
我正在保存登录user_id
信息以及所有其他服务详细信息。当用户上传一个 logo 文件时,这段代码在数据库中存储了两条记录:一条是正确的user_id
,另一条是0
. 当用户不上传标志文件时,只存储一条记录所有正确的值。
这里user_id
2 是正确的条目。请帮助我改进此代码。