【发布时间】:2017-11-13 07:41:51
【问题描述】:
我正在做一个项目,其中一部分是用户可以创建项目。
项目需要与用户耦合。如果用户在创建项目时已登录,那么没有问题,我可以将项目附加到经过身份验证的用户,但是当用户未登录时,我的表单中有以下部分
简而言之,有 2 个单选按钮,第一个表示“我有一个帐户,请登录”,其下方的登录字段。第二个意思是“我是新用户,创建一个帐户”,它将显示创建用户的正确字段。
由于此表单已添加到项目创建表单中,因此必须立即验证所有内容。
现在我有一个处理所有验证的 formRequest,但我在登录部分苦苦挣扎。
验证时,我必须检查以下事项:
1) 如果用户在开始填写表单时已经登录,但在存储数据时不再登录,那么我们必须将其添加到错误数组中
2)如果用户在开始填写表单时没有登录,而他选择通过上面解释的表单登录,那么我们需要在创建项目时尝试登录用户,并且当登录失败时向错误数组添加一条消息“提供了错误的凭据......”。
我已尝试使用以下 FormRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateJobsRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
if (! auth()->check()) {
if($this->get('is_logged_in')) {
// If we reach this, then we were logged in when starting to fill in the form
// but are no longer when finishing the form (idle for to long, ....).
$this->getValidatorInstance()->errors()->add('authentication', 'You were no longer authenticated when creating the project.');
}
if($this->get('auth_type') == 'login') {
if(! auth()->attempt($this->getLoginParams())) {
// if we reach this, we have chosen to log in through the form, bu the provided details did not match our records.
$this->getValidatorInstance()->errors()->add('authentication', 'Failed to authenticate');
}
}
}
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'login.email' => 'required_if:auth_type,login',
'login.password' => 'required_if:auth_type,login',
'register.email' => 'nullable|required_if:auth_type,register|email|max:255',
'register.password' => 'required_if:auth_type,register,confirmed|max:255',
'register.firstname' => 'required_if:auth_type,register|max:255',
'register.name' => 'required_if:auth_type,register|max:255',
'jobs.*.title' => 'required',
'jobs.*.description' => 'required',
'jobs.*.category_id' => 'required|exists:job_categories,id',
'jobs.*.location_id' => 'required|exists:job_locations,id',
'jobs.*.profiles' => 'required|numeric'
];
}
private function getLoginParams()
{
return ['email' => $this->get('login.email'), 'password' => $this->get('login.password')];
}
}
最重要的部分是在授权方法中。我正在尝试将项目添加到错误数组中,但它不起作用。
1) 如果规则函数的所有其他验证都通过了,那么我不会被重定向到创建页面,但代码会进入控制器并创建一个项目。
2) 如果不是所有其他验证都通过,那么我将被重定向到创建页面,但我在授权方法中添加的错误不会添加到错误中,因此不会显示在创建页面上。
【问题讨论】:
-
为什么你没有两个单独的表格。在第一种形式中使用操作登录,第二个应该注册。隐藏两个表单使用单选按钮根据需要显示隐藏。这样你的控制器会更好,你不必担心所有这些 if 和 else 检查
-
我认为因为在这两种情况下你都必须在
$this->getValidatorInstance()之后添加return false;!!
标签: php forms laravel validation