2015-06-10 288 views
0

你好,所以我一直在使用Laravel開始,它是有用的和容易。現在我有一個正在工作的CRUD。在我的AccountController @ store中,代碼是:Laravel雄辯創建

public function store(Request $request) 
{ 
    $input = $request->all(); 
    Accounts::create($un); 
    Session::flash('flash_message', 'Account successfully added!'); 
    return redirect()->route('accounts.index'); 
} 

這基本上在我的表中添加了一個新帳戶。我的問題是,我有一個密碼文本框,我不能哈希它,因爲此代碼會自動獲取表單中的每個輸入。我怎樣才能一一得到它?只有用戶名,電子郵件和密碼,所以我可以散列密碼。

+0

不要忘記做一些驗證之前創建一個用戶。 – Lucas

回答

3

您可以通過一個獲取輸入一個,然後散列密碼,並將其保存到數據庫中。但是那需要額外的代碼。

您還可以添加額外的功能,以您的帳戶模式,將自動照顧這一點。

看看我用它來創建我的管理用戶的例子。

<?php namespace App; 

use Illuminate\Auth\Authenticatable; 
use Illuminate\Database\Eloquent\Model; 
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; 

use Hash; 

class Management extends Model implements AuthenticatableContract { 

    use Authenticatable; 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'Management'; 

    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = ['name', 'email', 'password']; 

    /** 
    * The attributes excluded from the model's JSON form. 
    * 
    * @var array 
    */ 
    protected $hidden = ['password', 'remember_token']; 

    /** 
    * Automatic hash function for the password. 
    * 
    * @var array 
    */ 
    public function setPasswordAttribute($value) 
    { 
     $this->attributes['password'] = Hash::make($value); 
    } 

} 

關於你的代碼,你可以這樣做:

public function store(Request $request) 
{ 
    Accounts::create($request->all()); 
    Session::flash('flash_message', 'Account successfully added!'); 
    return redirect()->route('accounts.index'); 
} 

確保修改上面你自己的需求的示例的典範!

+0

我試過這個,並得到這個錯誤不能使用Authenticatable作爲Authenticatable,因爲名稱已被使用 – FewFlyBy

+0

我的錯對不起,它現在對你有用嗎? –

+0

等我犯了一個錯誤,我認爲 – FewFlyBy

0

你叫Input::all()獲得通過的所有屬性,並Input:get('key')得到一個特定的密鑰。

所以,你應該叫:

$account = new Accounts; 
$account->username = Input::get('username'); 
$account->password = Hash::make(Input::get('password')); 

//key with a default 
$account->password = Input::get('age', 20); 

//optional field 
if (Input::has('optional')) { 
    $account->optional = Input::get('optional'); 
} 

//any other fields that account needs 

$account->save() 
+0

{!! Form :: open(array('route'=>'accounts.store'))!!}是一個POST。現在嘗試你的代碼 – FewFlyBy

+0

你從哪裏得到新的Account()? – FewFlyBy

+0

帳戶是什麼類型的對象?我認爲這是一個雄辯的模型。 – soote

1

你也可以這樣做:

public function store(Request $request) 
{ 
    $input = $request->all(); 

    Accounts::create([ 
     'username' => $input['username'], 
     'password' => bcrypt($input['password']), 
    ]); 

    Session::flash('flash_message', 'Account successfully added!'); 
    return redirect()->route('accounts.index'); 
}