将 Post 与用户 ID 一起存储,在 Laravel 6 中引用用户 table

Store Post along with user id, referenced to User table in Laravel 6

我有 Post 和用户模型,关系如下: user_idposts 中的外键 table 引用了 users table 的 id

Post 型号

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

用户模型

public function posts () {
  return $this->hasMany(Posts::class, 'user_id', 'id');
}

还有一个 PostController 存储方法:

public function store(Request $request){
 $this->validate($request, [
  'title' => 'required|max:255',
  'desc' => 'required|max:255'
 ]);

 $image = null;
 $files = $request->thumbnail;
 $thumb = time().'.'.$files->getClientOriginalExtension();
 $request->thumbnail->move(public_path('public'),$thumb);
 $image = $thumb;
 $post = Posts::create([
   'title' => $request->title,
   'thumbnail' => $image,
   'user_id' => __________
   'desc' => $request->desc
 ]);
 return $post->toJson();                     }

考虑到这一点,我想实现这样一种关系:一个用户可以有很多帖子。 那么,如何借助 usersposts table 之间的关系来获取 userid 以插入帖子 table.
编辑:在上面的控制器中,我怎样才能得到 user_id 值??

这很容易。

你可以通过url获取id:

localhost:8000/users/{id}

在你的路线上[web.php]

Route::get('/users/{id}', 'UserController@show');

您的控制器:

<?php

namespace App\Http\Controllers;


class UserController extends Controller
{
    public function show($id)
    {
        return User::with('posts')->where('id',$id)->get()
    }

问题已更新所以答案必须更新:

登录后您应该使用以下代码:

您将通过 Auth facade 访问经过身份验证的用户:

// Get the currently authenticated user...
$user = Auth::user();

// Get the currently authenticated user's ID...
$id = Auth::id();

不要忘记命名空间

use Illuminate\Support\Facades\Auth;