dpblwmh5218 2015-01-20 20:44
浏览 110
已采纳

Laravel:无法将用户对象保存到数据库

I'm following this Laravel login/register tutorial on YouTube and I ran into a problem.

It seems I cannot insert the data from the $user object into my database. Everything I have so far works perfectly fine until I reach the $user->save() method.

The following is my AccountController.php. You'll notice that I'm using print_r to try and debug the process. The first print_r gets printed to my page, but the second never does: Laravel just stops and outputs a cryptic Whoops, looks like something went wrong. warning.

class AccountController extends BaseController {

    public function getCreate()
    {
        return View::make('account.create');
    }

    public function postCreate()
    {
        $validator = Validator::make(Input::all(), array(
                    'email' => 'required|max:64|min:3|email|unique:users',
                    'name' => 'required|max:64|min:3',
                    'password' => 'required|max:64|min:6'
        ));

        if ($validator->fails())
        {
            // Return to form page with proper error messages
            return Redirect::route('account-create')
                            ->withErrors($validator)
                            ->withInput();
        }
        else
        {
            // Create an acount
            $email = Input::get('email');
            $name = Input::get('name');
            $password = Input::get('password');

            // Activation code
            $code = str_random(64);
            $user = User::create(array(
                        'active' => 0,
                        'email' => $email,
                        'username' => $name,
                        'password' => Hash::make($password),
                        'code' => $code
            ));

            if ($user)
            {
                // Send the activation link
                Mail::send('emails.auth.activate', array(
                    'link' => URL::route('account-activate', $code),
                    'name' => $name
                        ), function($message) use($user) {
                    $message
                            ->to($user->email, $user->username)
                            ->subject('Jasl | Activate your new account');
                });

                return Redirect::route('home')
                                ->with('success', 'One more step! You\'ll get an email from us soon. Please follow the activation link to activate your account.');
            }
        }
    }

    public function getActivate($code)
    {
        // Find user whose code corresponds to the one we've previously sent through email
        $user = User::where('code', '=', $code)->where('active', '=', 0);

        if ($user->count())
        {
            $user = $user->first();

            $user->active = 1;
            $user->code = '';

            echo '<pre>', print_r($user), '<pre>';
            if ($user->save())
            {
                echo '-----------------------';
                echo '<pre>', print_r($user), '<pre>';
            }
        }
    }
}

I've googled a bit and found out that I should create a $fillable array in my User class, so I did it:

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

class User extends Eloquent implements UserInterface, RemindableInterface {

    protected $fillable = array('active', 'name', 'email', 'password', 'password_temp', 'code', 'salt', 'created_at', 'updated_at', 'pref_weight', 'pref_units', 'pref_time', 'pref_ener');

    use UserTrait,
        RemindableTrait;

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

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

}

Those are actually all the elements that my users table has.

This did not solve the problem.

What am I missing? Why isn't $user->save() working properly?

  • 写回答

1条回答 默认 最新

  • douhuan7862 2015-01-20 21:36
    关注

    I got it.

    My problem was that I created the id column of my users table with a custom name, user_id, instead of simply id. Apparently Laravel does not like this at all. The debugger pointed me to:

    C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Database\Connection.php
    

    with the error:

    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update users set active = 1, code = , updated_at = 2015-01-20 21:28:14 where id is null)

    I didn't know you shouldn't customize id columns. Renaming it solved the problem entirely and the database now updates correctly.

    Thanks @patricus for the useful debugging tip, that's what allowed me to track this error down.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图