Laravel - 在null

时间:2016-07-05 19:17:15

标签: php laravel controller laravel-5.2

我正在尝试通过控制器将表单详细信息保存到我的数据库中。当我点击提交时,我会看到此错误:

  

在ClinicController.php第58行中   ClinicController->存储(对象(请求))

第58行(整个功能见下文)是:

$request->user()->create([

控制器:

public function store(Request $request)
{

    $request->user()->create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => $request->password
    ]);

    $request->user()->clinic()->create([
        'clinic_name' => $request->clinic_name,
        'telephone' => $request->telephone,
        'address_1' => $request->address_1,
        'address_2' => $request->address_2,
        'city' => $request->city,
        'postcode' => $request->postcode
    ]);

    return redirect('/home');

}

用户模型:

public function clinic() {
    return $this->belongsTo(Clinic::class);
}

诊所模型:

public function user() {
    return $this->belongsTo(User::class);
}

routes.php文件:

Route::post('/clinic', 'ClinicController@store');

非常感谢任何帮助。非常感谢。

4 个答案:

答案 0 :(得分:1)

public function store(Request $request)
{
    $user = App\User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => $request->password
    ]);

    $clinic = App\Clinic::create([
        'clinic_name' => $request->clinic_name,
        'telephone' => $request->telephone,
        'address_1' => $request->address_1,
        'address_2' => $request->address_2,
        'city' => $request->city,
        'postcode' => $request->postcode
    ])

    $user->clinics()->attach($clinic->id);

    return redirect('/home');
}

答案 1 :(得分:0)

将您的控制器更改为:

public function store(Request $request)
{

    App\User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => $request->password
    ]);

    App\Clinic::create([
        'clinic_name' => $request->clinic_name,
        'telephone' => $request->telephone,
        'address_1' => $request->address_1,
        'address_2' => $request->address_2,
        'city' => $request->city,
        'postcode' => $request->postcode
    ]);

    return redirect('/home');

}

答案 2 :(得分:0)

如果您想要当前授权的用户,请使用app()->user()。此外,您可以简化许多逻辑并使其更容易阅读。

auth()
->user()
->create($request->only([
    'name', 
    'email', 
    'password'
]))
->clinic()
->create($request->only([
    'clinic_name', 
    'telephone', 
    'address_1', 
    'address_2', 
    'city', 
    'postcode'
]));

return redirect('/home');

答案 3 :(得分:0)

我认为$ fillable属性存在问题,请务必查看。