Tuesday, November 15, 2022

[FIXED] How to insert data with logged in user id? Laravel-6

Issue

I want to submit data to bidding table with logged in user id and auction id from product show method.

This is how my tables are in relation.

This is how my tables are in relation

Is it good to use ProductController or should I create another controller for bidding table?

Product show blade

 @extends('layouts.app')

 @section('content')

<div class="container">
  <div class="my-3 border">
    <div class="row">
      <div class="col-md-5">
        <img src="/storage/images/{{$product->image}}" alt="" style="width: 100%;">
      </div>
      <div class="col-md-7">
        <h2>{{$product->name}}</h2>
        <p>{{$product->description}}</p>
        <span>Category: {{$product->category->name}}</span><br>
        <span class="text-right">Auction Ends: {{$product->auction->deadline}}</span>
        <div class="price">Initial Price: {{$product->price}}</div>

        {!! Form::open(['action' => 'BiddingsController@create', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
          <div class="form-inline">
            {{Form::number('bidamount', '',['class' => 'form-control mr-1', 'placeholder' => 'Place your bid'])}}
            {{Form::submit('Place Bid', ['class' => 'btn btn-primary'])}}
          </div>
        {!! Form::close() !!}

@endsection

Bidding controller

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Bidding;

class BiddingsController extends Controller
{
    public function index()
    {
    $biddings = Bidding::all();

    return view('products.show' ,compact('biddings', $biddings));
}

public function create()
{
   //
}

public function store(Request $request)
{
    //
}

public function show(Bidding $bidding)
{
    //
}

}


Solution

In a Laravel 6 app, you can get the Logged in user using the auth() helper.

$authUser = auth()->user();

Doc: https://laravel.com/docs/6.x/helpers#method-auth

Cordially



Answered By - ml59
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.