首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel/Ardent/用户模型编辑+保存

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

Stack Overflow用户
提问于 2014-01-23 16:38:12
回答 2查看 1.9K关注 0票数 4

用laravel/ardent编辑带有密码的用户模型的目的是什么?我的问题是,在正确验证用户输入之前,我不希望从db加载实际的用户模型。当我将密码字段保留为空时,验证显然会失败,因为需要密码。这是我当前的编辑操作:

代码语言:javascript
复制
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'));
}

这似乎是相当多的代码(+它不起作用),我找不到这种情况的例子。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-25 16:48:48

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

问题是,如果没有给出新的密码,那么问题是将自动水化特性与保留旧密码的独特要求相结合。因为在validate()save()上都有大量的自水合物,所以也没有办法阻止自动补足空密码。首先,我试图更改输入数组并用旧密码覆盖它,但之后我只是关闭了用户模型的自动水合功能:

代码语言:javascript
复制
class User extends Ardent implements UserInterface, RemindableInterface {

    public $forceEntityHydrationFromInput = false;
    public $autoHydrateEntityFromInput = false;

这是POST上的编辑操作:

代码语言:javascript
复制
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'));
}
票数 2
EN

Stack Overflow用户

发布于 2014-08-11 03:17:40

我遇到了和你一样的问题。在搜索了一辈子之后,我阅读了阿登特代码,并想出了这个。它允许您使用一组规则、自动水合、自动散列密码和updateUnique()函数。我知道它可以被清理,我相信有更好的方法来做,但我已经花了很多时间在这个问题上。

这使用控制器(记录在这里)中的动态beforeSave()闭包。由于我们正在更新,我们检查是否有一个密码正在发送。如果没有密码,则将$rules数组中的密码验证设置为空,不包括验证中的密码。由于自动散列密码是在验证之后和beforeSave()之前发生的,所以我们需要关闭它(设置为false)。该模型在通过验证后第二次传播,因此提交的空白密码字段将在beforeSave()之前向其发出哈希,使其不再为空,并将无法通过第二次检查。在运行updateUniques()或Save()时,我们再次通过beforeSave闭包检查是否提交了密码,如果没有,则将其从更新中删除。

dr以最小的代码防止在管理更新上要求和/或删除密码。

型号:

代码语言:javascript
复制
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',
);

主计长:

代码语言:javascript
复制
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());
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21314130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档