Home > Software design >  laravel 8 add row and write userid automatically?
laravel 8 add row and write userid automatically?

Time:02-22

I followed this quida, and everything works, but I need that the userid field is automatically written with the id of the logged in user, how can I do it? how can i add this to this code?

Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\ProductStock;

class ProductAddMoreController extends Controller

{

/**

 * Display a listing of the resource.

 *

 * @return \Illuminate\Http\Response

 */

public function addMore()

{

    return view("addMore");

}



/**

 * Display a listing of the resource.

 *

 * @return \Illuminate\Http\Response

 */

public function addMorePost(Request $request)

{

    $request->validate([

        'addmore.*.name' => 'required',

        'addmore.*.qty' => 'required',

        'addmore.*.price' => 'required',

    ]);



    foreach ($request->addmore as $key => $value) {

        ProductStock::create($value);

    }



    return back()->with('success', 'Record Created Successfully.');

}

}

view:

<!DOCTYPE html>

<html>

<head>

    <title>Add/remove multiple input fields dynamically with Jquery Laravel 5.8</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

</head>

<body>

   

<div >

    <h2 align="center">Add/remove multiple input fields dynamically with Jquery Laravel 5.8</h2> 

   

    <form action="{{ route('addmorePost') }}" method="POST">

        @csrf

   

        @if ($errors->any())

            <div >

                <ul>

                    @foreach ($errors->all() as $error)

                        <li>{{ $error }}</li>

                    @endforeach

                </ul>

            </div>

        @endif

   

        @if (Session::has('success'))

            <div >

                <a href="#"  data-dismiss="alert" aria-label="close">×</a>

                <p>{{ Session::get('success') }}</p>

            </div>

        @endif

   

        <table  id="dynamicTable">  

            <tr>

                <th>Name</th>

                <th>Qty</th>

                <th>Price</th>

                <th>Action</th>

            </tr>

            <tr>  

                <td><input type="text" name="addmore[0][name]" placeholder="Enter your Name"  /></td>  

                <td><input type="text" name="addmore[0][qty]" placeholder="Enter your Qty"  /></td>  

                <td><input type="text" name="addmore[0][price]" placeholder="Enter your Price"  /></td>  

                <td><button type="button" name="add" id="add" >Add More</button></td>  

            </tr>  

        </table> 

    

        <button type="submit" >Save</button>

    </form>

</div>

   

<script type="text/javascript">

   

    var i = 0;

       

    $("#add").click(function(){

   

          i;

   

        $("#dynamicTable").append('<tr><td><input type="text" name="addmore[' i '][name]" placeholder="Enter your Name"  /></td><td><input type="text" name="addmore[' i '][qty]" placeholder="Enter your Qty"  /></td><td><input type="text" name="addmore[' i '][price]" placeholder="Enter your Price"  /></td><td><button type="button" >Remove</button></td></tr>');

    });

   

    $(document).on('click', '.remove-tr', function(){  

         $(this).parents('tr').remove();

    });  

   

</script>

  

</body>

</html>

Does anyone know how to help me insert userid in the database automatically, I don't need to see it in the table but I need it to be registered in the database with these associated fields

CodePudding user response:

Laravel includes built-in authentication and session services which are typically accessed via the Auth and Session facades. Userid can be obtained like this Auth::user()->id Use this identifier in your code ProductAddMoreController for ProductStock model.

CodePudding user response:

There is more than one way to do this, you might do it using Model observers or you can do it by adding user_id value manually to create method.

First you need to have the user_id column in your products_stocks DB table, you can add it to your up() method in your migration using something like:

public function up()
{
    Schema::table('products_stocks', function (Blueprint $table) {
        $table->unsignedBigInteger('user_id')->nullable();

        $table->foreign('user_id')
            ->references('id')->on('users')
            ->onDelete('cascade')->onUpdate('cascade');
    });
}

then in your controller add the user_id to create() method:

// ...

foreach ($request->addmore as $key => $value) {
    ProductStock::create(array_merge($value, ['user_id' => auth()->user()->id]));
}

// ...
  • Related