【发布时间】:2020-07-08 15:57:34
【问题描述】:
我只是laravel的初学者,如果这是一个愚蠢的问题,对不起
这是我的控制器:-
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Profile;
use Auth;
class ProfilesController extends Controller
{
public function _construct()
{
$this->middleware('auth');
}
public function create()
{
return view('bio');
}
public function store(Request $request)
{
auth()->user()->profile()->user_id;
// create Bio
$profile = new Profile;
$profile->bio = $request->input('bio');
$profile->save();
return redirect('/home');
}
}
这是我的模型:-
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $gaurded = [];
protected $fillable = ['user_id', 'bio'];
public function user()
{
return $this->belongsTo(User::class);
}
}
这是我的桌子
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $gaurded = [];
protected $fillable = ['user_id', 'bio'];
public function user()
{
return $this->belongsTo(User::class);
}
}
这是我的用户模型:-
public function profile()
{
return $this->hasOne(Profile::class);
}
public function posts()
{
return $this->hasMany(Posts::class);
}
我收到此错误 "Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$user_id" 我不知道我哪里出错了请帮助我并指导我你可以 谢谢
【问题讨论】:
-
仅供参考,
$gaurded中的错字。auth()->user()->profile()->user_id;应该做什么? -
auth()->user()->profile->user_id;而不是auth()->user()->profile()->user_id; -
正如你所说@TsaiKoga 我试过 "auth()->user()->profile->user_id;" 但我得到的错误是这个 "试图获取非对象“的属性'user_id'
-
@AnonymousChatbox 因为配置文件是无,这意味着用户没有配置文件。你为什么不直接使用
$id = auth()->id(); -
这是我得到的 "SQLSTATE[HY000]: 一般错误:1364 字段 'user_id' 没有默认值" 我也是编码新手所以如果你对我的愚蠢感到生气,我很抱歉
标签: php laravel relationship