Laravel Nullable没有工作,我尝试了所有的方法,但它仍然不工作。请看我的代码..
控制器:-
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Pop;
class PopController extends Controller
{
public function index(){
return view('test2');
}
public function create(Request $request){
$formvalidtion = $request->validate([
'usercode' => ['nullable', 'required'],
]);
return "<h1>SUCCESS</h1>";
}
}型号:-
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pop extends Model
{
protected $timestamps = false;
protected $fillable = ['usercode'];
}迁移:-
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePopsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('pops', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('usercode')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('pops');
}
}路线:
route::get('test', 'PopController@index');
route::post('testcheck', 'PopController@create')->name('uc');查看:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Nullable Test</title>
</head>
<body>
<h1>Test Nullable</h1>
<form action="{{ route('uc') }}" method="POST">
@csrf
<input type="number" name="usercode" id="" placeholder="Enter User Code">
@error('usercode')
{{ $message }}
@enderror
<br>
<input type="submit" >
</form>
</body>
</html>我花了1个小时来寻找答案,但没有得到。一些youtube视频提到字段数据类型必须是int且可以为空。这也不起作用,有没有可用的解决方案?
发布于 2020-03-03 21:51:23
同时使用nullable和required验证规则是不正确的:
required:验证字段必须存在于输入数据中且不能为empty.nullable:验证字段可以为null.present:验证字段必须存在于输入数据中但可以为empty.filled:验证字段为present.prohibited:时不能为空验证字段必须为空或不为present.sometimes:验证字段仅在以下情况下才会被验证它是present.exclude:将从validate和validated方法返回的请求数据中排除验证字段。您可以同时使用nullable和present:
$formvalidtion = $request->validate([
'usercode' => ['nullable', 'present'],
]);发布于 2020-03-03 21:50:07
您没有指定“不工作”是什么意思(即,您期望的是什么,但实际上发生了什么),但我假设您的意思是空值不被验证接受。
这是因为required rule需要一个非空的值。因此,您的nullable规则可能通过了,但是required失败了。
如果您想要一个值存在,但不一定非空,您可以使用present rule。
https://stackoverflow.com/questions/60508606
复制相似问题