B. All
B. All

Reputation: 69

-Laravel 5.2 insert logged in users foreign key automatically into product table when creating product

i've been working on a CRUD system lately, what i want is that when a logged in user creates a product on my website his name will automatically be inserted as a foreign key into my product table.

this is my Product model i've made for it.

//inkoopprijs = sell price
//verkoop prijs = buy price
//naam = product name


protected $fillable = ['naam', 'inkoopprijs', 'verkoopprijs','users_id','created_at', 'updated_at'];

protected $table = "product";

this is my ProductController store function

 public function store(Request $request)
{  
   $product = Product::create($request->only(['naam', 'inkoopprijs', 'verkoopprijs', 'users_id']));

   return redirect(route('product.index'));  
}

Upvotes: 0

Views: 558

Answers (3)

Raphaël B
Raphaël B

Reputation: 28

You can access the current logged in user with Auth::user(); or auth()->user();

We can also access the identifier with Auth::id();

Product::create([
    'naam' => $request->get('naam'),
    'inkoopprijs' => $request->get('inkoopprijs'),
    'verkoopprijs' => $request->get('verkoopprijs'),
    'users_id' => \Auth::id()
]);

I hope this is what you meant.

Upvotes: 1

manian
manian

Reputation: 1438

You can use users id as hidden field in the form but need to consider the security aspects of using users id in the form. It depends on where you are using. May be you can use this method is the user is already authenticated.

<input type="hidden" name="users_id" value="{{Auth::user()->id}}">

Upvotes: 1

Paras
Paras

Reputation: 9465

You can do this with Eloquent events like so:

Product::creating(function ($product) {
    $user = auth()->user();
    $product->users_id = $user->id;
});

Upvotes: 2

Related Questions