添加外键请求 Laravel

Add foreign key to request Laravel

我想要实现的是: 用户通过标题输入创建交付,
当用户发送请求时,我想获取 users_id 以将其作为外键添加到交付 table 中。 这是交货 table

     public function up()
{
    Schema::create('deliveries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->integer('users_id')->unsigned();
        $table->timestamps();
    });

    Schema::table('deliveries', function ($table) {


        $table->foreign('users_id')->references('id')->on('users');
    });
}

这里是 DeliveryController

    <?php

   namespace App\Http\Controllers;

   use Illuminate\Http\Request;

   use App\Http\Requests;

   use App\User;

   class DeliveryController extends Controller
   {
       public function index()
       {
           return view('delivery.index');
       }

       public function create()
       {
           return view('delivery.create');
       }

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

          $input = $request->all();

          $input['users_id'] = Auth::user()->id;

          Delivery::create($input);

          return redirect()->back();
       }

   }

您可以通过两种方式进行

方法 1) 获取 user_id 并像 :

一样手动插入
$user_id = User::select('id')->where('id',$request->user()->id)->get(); 
Or use this bit to get the current loggedin user_id : $request->user()->id

方式 2) 使用 Eloquent 模型

在用户模型中创建关系,例如:hasMany、ManyToMany 或 OneToOne,具体取决于适合您的那个。

public function deliveries()
    {
        return $this->hasMany('App\User');
    }

只需调用此 $user->deliveries() 即可自动插入 user_id

我猜你的代码有问题:

$input = $request->all();

$input['users_id'] = Auth::user()->id;

Delivery::create($input);

你能试试这个吗:

$delivery= new Delivery;//here Delivery is the Model name
$delivery->title         = Input::get('title');
$delivery->user_id       = $request->user()->id;
$delivery->save();

经过数周的研究,我发现我的控制器缺少这一行:

    use Illuminate\Support\Facades\Input;