繁体   English   中英

未定义的属性:Illuminate\\Database\\Eloquent\\Relations\\HasOne::$user_id

[英]Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$user_id

我只是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);
    }

我收到此错误“未定义的属性:Illuminate\\Database\\Eloquent\\Relations\\HasOne::$user_id”我不知道我哪里出错了,如果可以,请帮助我并指导我谢谢

您不能在Illuminate\\Database\\Eloquent\\Relations\\HasOne profile()上调用属性user_id

您可以通过auth()->user()->profile->user_id调用它。

但是,该用户还没有个人资料。 需要创建它并在Illuminate\\Database\\Eloquent\\Relations\\HasOne上使用create方法,Laravel 会自动构建 foreign_key user_idprofile

  public function store(Request $request)
  {
      auth()->user()->profile()->create([
         'bio' => $request->input('bio')
      ]);
      return redirect('/home');
  }

在您的个人资料模型中

public function profile()
{
  return $this->hasOne(Profile::class,"user_id","id");
}

在您的控制器中

  public function store(Request $request)
  {
       echo $id = auth()->user->profile->user_id; 
       $input = $request->all();
       $input['user_id'] = auth()->id(); // OR auth()->user->profile->user_id;
       Profile::create($input);
       return redirect('/home');
  }

您需要在用户模型中定义外键和本地键的关系,如下所示:

public function profile()
{
  return $this->hasOne(Profile::class,"user_id","id");
}

我猜你的目标是定义一对一的关系。

为此,您需要在用户模型中定义一个 hasOne 关系

public function profile()
{
    return $this->hasOne(Profile::class);
}

和个人资料模型中的属于

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

并且不要忘记将 user_id 放在您的配置文件表中。

检查此 链接以获取更多信息

在这些步骤之后,如果您有登录(经过身份验证的)用户,您可以使用以下命令获取配置文件表的 user_id 字段:

use Illuminate\Support\Facades\Auth;


Auth::user()->profile->user_id; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM