【问题标题】:Laravel : add new row in model tableLaravel:在模型表中添加新行
【发布时间】:2014-04-07 22:54:12
【问题描述】:

我定义了一个用户模型,我正在尝试使用表单在我的数据库中添加一个新用户,最好和最快的方法是什么,我已经阅读了一些关于模型表单绑定的内容,但我认为它是只是为了更新而不是添加新行。

我是 Laravel 新手,找不到一些好的教程,我必须认识到 Laravel 文档真的很差,所以欢迎任何指向一些好的和解释清楚的教程的链接。 谢谢

【问题讨论】:

  • 当您的$fillable 在模型中正确设置时,您可以像User::create(Input::all()) 一样简单地创建一个新行。这是一个简单的 crud 教程,看起来不错,scotch.io/tutorials/…

标签: php laravel laravel-4 form-submit


【解决方案1】:

假设您有一个User 模型(app/models/User.php),默认情况下带有Laravel,它可能看起来像这样:

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {
    
    protected $table = 'users';
    protected $hidden = array('password');

    public function getAuthIdentifier()
    {
        return $this->getKey();
    }
    
    public function getAuthPassword()
    {
        return $this->password;
    }

    public function getReminderEmail()
    {
        return $this->email;
    }
}

现在,从控制器(基本上)你可以使用这样的东西:

$user = new user;
$user->username= 'Me';
$user->email = 'me@yahoo.com';
// add more fields (all fields that users table contains without id)
$user->save();

还有其他方式,例如:

$userData = array('username' => 'Me', 'email' => 'me@yahoo.com');
User::create($userData);

或者这个:

User::create(Input::except('_token'));

这要求您在 User 模型中使用如下属性:

class User extends Eloquent implements UserInterface, RemindableInterface {

    protected $fillable = array('username', 'email');

    // Or this,  (Read the documentation first before you use it/mass assignment)
    protected $guarded = array();

}

由于您还是 Laravel 的新手,您可以使用第一个示例并阅读有关 Mass Assignment 的内容,然后您可以根据需要使用第二个示例。

更新:

在你的控制器中,你可以使用Input::get('formfieldname')来获取提交的数据,例如:

$username = Input::get($username);

因此,您可以像这样使用这些数据:

$user = new User;
$user->username= $username;

也可以直接使用:

$user->email = Input::get($email);
$user->save();

在表单中,您必须设置form action,您将在其中提交表单,在这种情况下您必须声明一个路由,例如:

Route::post('user/add', array('as' => 'user.add', 'uses' => 'UserController@addUser'));

然后在你的控制器中你必须创建方法addUser,像这样:

class UserController extends addUser {
    
    // other methods
    
    public function addUser()
    {
        $user = new user;
        $user->username = Input::get('username');
        $user->email = Input::get($email);
        $user->save();
    }
}

在你的表单中你可以使用这个:

Form::open(array('route' => 'user.add'))

正确阅读the documentation,你可以轻松做到。

【讨论】:

  • 没错,但是我将如何从表单获取用户名和电子邮件到控制器,我已经尝试过 Form::open(array('url'=>'url_of_controller')) 但没有没用
  • $user->usaername --> $user->username
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 2018-01-15
  • 1970-01-01
  • 2015-11-13
  • 2014-03-17
  • 1970-01-01
相关资源
最近更新 更多