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.

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

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R