Laravel获取最新插入的用户

时间:2016-11-28 10:50:02

标签: php mysql laravel eloquent laravel-5.3

我正在使用Laravel Auth让用户能够注册。我现在正在尝试的是:在用户注册后(如果他们选择了特殊角色),另一行插入另一个表(然后是用户),其中包含相关的用户ID。这是它的代码:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use App\Complaint;


class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'username' => 'required|unique:users',
            'role' => 'required'
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {

        $user = new User;
        $user->name = $data['name'];
        $user->email = $data['email'];
        $user->username = $data['username'];
        $user->password = bcrypt($data['password']);
        $user->role = $data['role'];
        $user->templateURL = "";

        /*$user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'username' => $data['username'],
            'password' => bcrypt($data['password']),
            'role' => $data['role'],
            'templateURL' => ""
        ]);*/

        $user->save();


        if($data['role'] == 'Verkäufer'){
            $complaintRow = Complaint::create([
               'user_id' => $user->id,
                'complaintCount' => 0
            ]);
        }


        switch($data['role']){
            case 'Käufer':
                $user->attachRole(2);
                break;
            case 'Verkäufer':
                $user->attachRole(3);
                break;
            default:
                $user->attachRole(2);
                break;
        }


        return $user;
    }
}

但它没有正常工作,插入用户以及投诉的行,但不知怎的$user->id似乎为空,列始终将user_id设置为0.任何想法为什么这可能是这样的吗?

编辑:我现在正在使用它...实际上不是我发布的代码,我只是没有在user_id中填写complaint字段table,这就是为什么总是有0,因为0是默认值,所以它没有设置它。

无论如何,谢谢大家的答案。

6 个答案:

答案 0 :(得分:2)

根据Laravel Eloquent ORM,$user->id将返回用户的ID。 如果您得到null,那么保存可能会出错。 (https://stackoverflow.com/a/21084888/6628079

保存后尝试打印$user

<强>更新 如果成功保存用户,最好在投诉表中添加数据。

protected function create(array $data)
{

    $user = new User;
    $user->name = $data['name'];
    $user->email = $data['email'];
    $user->username = $data['username'];
    $user->password = bcrypt($data['password']);
    $user->role = $data['role'];
    $user->templateURL = "";

    /*$user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'username' => $data['username'],
        'password' => bcrypt($data['password']),
        'role' => $data['role'],
        'templateURL' => ""
    ]);*/

    if ($user->save()) {
        if ($data['role'] == 'Verkäufer') {
            $complaintRow = Complaint::create([
                'user_id' => $user->id,
                'complaintCount' => 0
            ]);
        }


        switch ($data['role']) {
            case 'Käufer':
                $user->attachRole(2);
                break;
            case 'Verkäufer':
                $user->attachRole(3);
                break;
            default:
                $user->attachRole(2);
                break;
        }


        return $user;
    } else {
        // Your code if user doesn't save successfully.
    }
}

答案 1 :(得分:1)

这是因为,Eloquent保存方法bool,而不是新创建的实体的实例。如需确认,请点击此链接:https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html

因此,如果您想获取新创建的实例,您可以使用用户创建方法或进行另一个查询来获取新插入的实例。第一个更容易和容易。以下是如何做到这一点:

$user = User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'username' => $data['username'],
    'password' => bcrypt($data['password']),
    'role' => $data['role'],
    'templateURL' => ""
]);

现在,您拥有包含$user实例的User变量。但要做到这一点,您需要考虑模型中的可填写/保护问题。我的意思是,在你的模型中你必须添加以下行:

protected $fillabe = ['name', 'email', 'username', 'password', 'role', 'templateURL']

答案 2 :(得分:1)

id是否存在? 尝试在模型(用户)上设置$primaryKey = 'id'

$user->save之后,您可以id访问$user->id 或者$user->save尝试从您的表中获取最大ID。

$user = User::select('id')->max('id')->first();

答案 3 :(得分:0)

试试这个:

//your current set
let mySet : NSSet
//targetted index
let index : Int
//get object in set at index
let object = mySet.allObjects[index]

答案 4 :(得分:0)

$user->id会在使用save()方法后立即告诉您创建的用户ID。

答案 5 :(得分:0)

你做的最正确,你只需要改变,

  

当您保存用户对象时,它将返回已保存的用户对象,因此只需抓取该对象并在furcher条件中使用。

$saved_user = $user->save();

if(!empty($saved_user)){
      if($data['role'] == 'Verkäufer')
        {
                    $complaintRow = Complaint::create([
                       'user_id' => $saved_user->id,
                        'complaintCount' => 0
                    ]);
                }
  } else {
     throw new error(500);

}

希望这有助于谢谢:)