Laravel/Ardent/用户模型编辑 保存



用laravel/ardent中的密码编辑用户模型的预期方法是什么?我的问题是,在正确验证用户输入之前,我不想从数据库加载实际用户模型。当我将密码字段留空时,验证显然会失败,因为需要密码。这是我目前的编辑后:

public function postEdit($id)
{
    // ardent autohydrates this model
    $newUser = new User;
    // validation fails
    if(!$newUser->validate())
        return Redirect::action('UsersController@getEdit', $id)
            ->with('error', Lang::get('Bitte Eingabe überprüfen'))
            ->withErrors($newUser->errors())
            ->withInput(Input::except('password'));
    // load model from db
    $exUser = User::find($id);
    if(!$exUser->exists)
        return Response::make('No such user', 500);
    // save model, ardent autohydrates again?
    if($exUser->save())
        return Redirect::action('UsersController@getShow', $id)
            ->with('success', Lang::get('Änderungen gespeichert'));
    else
        return Redirect::action('UsersController@getEdit', $id)
            ->with('error', Lang::get('Bitte Eingabe überprüfen'))
            ->withErrors($newUser->errors())
            ->withInput(Input::except('password'));
}

这似乎是很多代码( 它不起作用),我找不到这种情况的示例

好吧,我自己解决了,因为这不是一个非常活跃的话题。

问题是将Ardents自动水合功能和保留旧密码的独特要求(如果没有新的)结合在一起。由于validate()save()上的Ardent自动水合物,因此也无法防止自动化合空密码。首先,我尝试更改输入阵列并使用旧密码覆盖它,但是后来我只是关闭了用户模型的自动水域:

class User extends Ardent implements UserInterface, RemindableInterface {
    public $forceEntityHydrationFromInput = false;
    public $autoHydrateEntityFromInput = false;

这是帖子上的编辑操作:

public function postEdit($id)
{
    // manually insert the input
    $user = new User(Input::all());
    // validate the user with special rules (password not required)
    if($user->validate(User::$updateRules)) {
        // get user from database and fill with input except password
        $user = User::find($id);
        $user->fill(Input::except('password'));
        // fill in password if it is not empty
        // will flag the pw as dirty, which will trigger rehashing on save()
        if(!empty(Input::get('password')))
            $user->password = Input::get('password');
        if($user->save())
            return Redirect::action('UsersController@getIndex')
                ->with('success', Lang::get('Änderungen gespeichert'));
    }
    return Redirect::action('UsersController@getEdit', $id)
        ->with('error', Lang::get('Bitte Eingaben überprüfen'))
        ->withErrors($user->errors())
        ->withInput(Input::except('password'));
}

我与您遇到了同一问题。在永远搜索之后,我阅读了热心的代码,并提出了这一点。它允许您使用一组规则,自动水合,自动哈希密码和Ardent的UpdateUnique()函数。我知道可以清理它,我敢肯定有一种更好的方法来做到这一点,但是我已经花了很多时间在这个问题上。

这使用控制器中的动态beforesave()闭合(在此记录)。由于我们正在更新,因此我们检查是否正在发送密码。如果没有密码,则将$规则数组中的密码验证设置为空白,不包括验证中的密码。由于自动哈希密码在验证后,并且在beforesave()之前发生,因此我们需要将其关闭(设置为false)。通过验证后的第二次传播该模型,因此提交的空白密码字段将在Beforesave()之前发出HASH,使其不再空白,并且将使我们的第二次检查失败。运行updateuniques()'或save()'时,我们通过提交密码再次通过beforesave关闭检查,如果不提交密码,请从更新中删除。

tl; dr以最小的代码在管理更新中需要和/或删除密码的热心自动水合。

模型:

class User extends Ardent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
// Auto Hydrate
public $autoHydrateEntityFromInput   = true;
public $forceEntityHydrationFromInput   = true;
public $autoPurgeRedundantAttributes    = true;
// Auto hash passwords
public static $passwordAttributes  = array('password');
public $autoHashPasswordAttributes = true;
protected $table  = 'users';
protected $guarded  = array('id','created_at','updated_at');
protected $hidden = array('password');
protected $fillable = array('first_name','last_name','employee_id','position','email','password');
public static $rules = array(
    'first_name'            => 'required',
    'last_name'             => 'required',
    'employee_id'           => 'required|max:10',
    'position'              => 'required',
    'email'                 => 'required|email|unique',
    'password'              => 'required|alpha_num|min:6',
);

控制器:

public function update($id)
{
    $user = User::find($id);
    // Check if a password has been submitted
    if(!Input::has('password')){
    // If so remove the validation rule
      $user::$rules['password'] = '';
    // Also set autoHash to false;
      $user->autoHashPasswordAttributes = false;
    }
    // Run the update passing a Dynamic beforeSave() closure as the fourth argument
    if($user->updateUniques(
      array(),
      array(),
      array(),
      function($user){
    // Check for the presence of a blank password field again
        if(empty($user->password)){
    // If present remove it from the update
          unset($user->password);
          return true;
        }
      })
    ){
      Alert::success('User Updated')->flash();
      return Redirect::route('admin.users.index');
    }
        Alert::add('form','true')->flash();
    return Redirect::back()
      ->withInput(Input::except('password'))
      ->withErrors($user->errors());
}

最新更新