亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

default() 在 Laravel 遷移中不起作用

default() 在 Laravel 遷移中不起作用

PHP
繁花如伊 2023-07-08 22:07:35
我正在使用 laravel 創建一個待辦事項列表,并且我有一個包含以下各列的表格:'標題'、'描述'、'已完成'、'id'每當我向表中添加新任務時,都會自動設置“已完成”列,其默認值為 0,其編碼如下:$table->boolean('completed')->default(0);該列工作得很好,但是當我嘗試為“描述”提供默認值(通過為描述保留空輸入)時,它會給出“完整性約束違規:1048 列“描述”不能為空”錯誤。我為“描述”列編寫的代碼如下:$table->string('description')->default('-');我嘗試了 text() 數據類型,但它給了我同樣的錯誤。我還嘗試對此列使用 nullable() ,但默認值 '-' 不會添加到該列中,并且它返回一個空值。我用來添加值的表單如下所示:<form action="/create" class="panel" method="post">    @csrf    <input name="title" type="text" class="title">    <textarea name="description" class="title"></textarea>    <input type="submit" class="submit"></form>我的控制器存儲方法:public function createTask(validation $request){        $userId = auth()->id();        $request['user_id'] = $userId;        Task::create($request->all());        return redirect()->route('showList');    }和表創建語句:CREATE TABLE `tasks` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `completed` tinyint(1) NOT NULL DEFAULT 0, `user_id` bigint(20) unsigned NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `description` text COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT ' ', PRIMARY KEY (`id`), KEY `tasks_user_id_foreign` (`user_id`), CONSTRAINT `tasks_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
查看完整描述

1 回答

?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

看到創建表語句和存儲函數后。看來您的商店功能更有可能是這里的問題。嘗試這個:


use Illuminate\Support\Facades\Auth;


public function createTask(Request $request){

? ? $user = Auth::user();//get the user model

? ? $request->validate([//validate that the data is according to limitations

? ? ? ? 'title' => 'required|max:255',

? ? ? ? 'description' => 'max:1000',

? ? ]);

? ? $task = new Task;? //create a new instance of Task

? ? //fill in the data

? ? $task->title = $request->input('title');

? ? if(!empty($request->input('description')){

? ? ? ? $task->description = $request->input('description');

? ? }

? ? $task->user_id = $user->id;

? ? $task->save();//save it

? ??

? ? return redirect()->route('showList');

}

對于批量分配,您應該將數據庫字段定義為可在您的Modelwith中批量分配protected $fillable = ['title','description','user_id']。


查看完整回答
反對 回復 2023-07-08
  • 1 回答
  • 0 關注
  • 186 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號