面对提交表单数据的问题。
当我填写所有表单数据时,它将被插入到数据库中。但是,当我只填写必填字段数据并将其他数据保留为空白时,它无法正常工作并重定向到相同的表单。
删除验证时也无效。
我的控制器功能代码:
public function save(Request $request) {
try {
$validator = Validator::make($request->all(), Activity::rules());
$activity = Activity::saveOrUpdate($request);
if($activity !== false) {
return redirect()->route('lists-activity')->with('success', trans('activity data added successfully.!!'));
} else {
return back()->with('error', "Unable to save activity data.!!")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save activity data.!!")->withInput()->withErrors($validator);
}
}
我的型号代码:
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class Activity extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'category_id',
'title',
'description',
'country_id',
'city_id',
'latitude',
'longitude',
'addressOne',
'addressTwo',
'hours_recomended',
'hours_fixed',
'time_fixed',
'start_time',
'end_time',
'file_type',
'flag_image'
];
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
public static function rules() {
return [
'category_id' => 'required',
'title' => 'required|string|max:255',
'country_id' => 'required',
'city_id' => 'required',
'hours_fixed' => 'required',
'start_time' => 'required',
'end_time' => 'required'
];
}
public static function saveOrUpdate(Request $request) {
try {
$id = $request->get('id', false);
$activity = false;
DB::transaction(function () use ($request, &$activity, $id) {
$activity = $id ? Activity::findOrFail($id) : new Activity();
$activity->fill($request->all());
try {
$activity->save();
} catch (\Exception $ex) {
throw $ex;
}
});
return $activity;
} catch (\Exception $ex) {
throw $ex;
}
} }
答案 0 :(得分:0)
看起来验证工作正常,并按照预期重定向。
将{{ dump($errors->all()) }}
添加到视图中,您在提交表单后会在表单中看到错误。
另外,请使用updateOrCreate()
,这正是您尝试做的事情,并会帮助您避免错误:
public static function saveOrUpdate(Request $request) {
return $this->updateOrCreate(['id' => $request->id], $request->all());
}