嗨,这是我的观点:
<form role="form" class="form" action="{{ url('/users/settings/notifications/notifications-settings') }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="checkbox" class="flat-orange" name="notification_type1" value="1" @if(in_array(1,$user_notifications ) == 1)checked @endif>
<input type="checkbox" class="flat-orange" name="notification_type2" value="2" @if(in_array(2, $user_notifications ) == 2)checked @endif>
<input type="checkbox" class="flat-orange" name="notification_type3" value="3" @if(in_array(3, $user_notifications ) == 3)checked @endif>
<input type="checkbox" class="flat-orange" name="notification_type4" value="4" @if(in_array(4,$user_notifications ) == 4)checked @endif>
<button type="submit" class="btn save-lang">@lang('buttons.save_changes')</button>
</form>
这里有我的路线:
Route::get('/settings/notifications/notifications-settings', 'UserSettingController@getNotificationsSettings');
Route::post('/settings/notifications/notifications-settings', 'UserSettingController@setNotificationsSettings');
这里我有我的控制器: class UserSettingController扩展Controller
{
public function getNotificationsSettings(){
$user_notifications = UserNotificationType::select('notification_type')->where('user_id', Auth::user()->id)->get()->toArray();
$user_notifications = array_map(function($user_notifications){
return $user_notifications['notification_type'];
}, $user_notifications);
return view('website.settings.notifications.notifications-settings')->with(['user_notifications' => $user_notifications]);
}
public function setNotificationsSettings( Request $request){
for ($i = 1; $i <= 4; $i++) {
$update_user_notifications = UserNotificationType::create([
'user_id' => Auth::user()->id,
'notification_type' => $request['notification_type'.$i] ?? false
]);
dd( $update_user_notifications);
}
return redirect()->back()->with(['status' => 'Notification Settings updated successfully.']);
}
}
型号:
public $timestamps = false;
protected $fillable = [
'user_id',
'notification_type',
];
我需要能够在第二次创建后能够更新而不创建其他4个我需要在同一个函数上执行此操作 enter image description here
有人可以帮助我,我是编码的新手,有没有办法实现我想要的......
答案 0 :(得分:0)
在数据库表结构中,notification_type
列
ALTER TABLE user_notification_types CHANGE notification_type notification_type INT(11) NULL;
答案 1 :(得分:0)
你应该使用雄辩的关系。
在用户模型上:
``` public $ timestamps = false;
protected $fillable = [
'user_id',
'notification_type',
];
public function notificationTypes () {
return $this->hasMany(UserNotificationType::class);
}
```
然后在你setNotificationsSettings
你可以这样做:
```
for ($i = 1; $i <= 4; $i++) {
$notificationTypes[] = $request['notification_type' . $i];
}
$user = Auth::user();
$user->notificationTypes()->sync(notificationTypes);
```
请参阅https://laravel.com/docs/5.6/eloquent-relationships#many-to-many