Abdel Maimouni
Abdel Maimouni

Reputation: 1

Add foreign key to request Laravel

what i am trying to achieve is : User create a Delivery by a title input,
When the user send the request i want to get the users_id to add it to delivery table as a foreign key. Here is the deliveries 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');
    });
}

here is the 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();
       }

   }

Upvotes: 0

Views: 2201

Answers (2)

Abdel Maimouni
Abdel Maimouni

Reputation: 1

After weeks of researches i found That my Controller Missing This Line :

    use Illuminate\Support\Facades\Input; 

Upvotes: 0

Murlidhar Fichadia
Murlidhar Fichadia

Reputation: 2609

You can do in Two ways

Way 1) Get the user_id and insert it manually like :

$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

Way 2) Use Eloquent Models

Create a relationship in User Model such as : hasMany, ManyToMany or OneToOne depending on the one that works for you.

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

And simply call this $user->deliveries() to insert user_id automatically.

I guess the problem with your code is here :

$input = $request->all();

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

Delivery::create($input);

Can you try this :

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

Upvotes: 1

Related Questions