Storing data from a form into a pivot table in Laravel requires a few steps. Here's how

I am currently working on storing data from a form to a pivot table called asset_user.

User Model:

public function assets()
{
    return $this->belongsToMany(Asset::class)->withPivot(['amount']);
}

Asset Model:

public function users()
{
    return $this->belongsToMany(User::class)->withPivot(['amount']);
}

Migration for asset_user:

public function up()
{
    Schema::create('asset_user', function (Blueprint $table) {
        $table->foreignId('asset_id')->unsigned()->index();
        $table->foreignId('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('asset_id')->references('id')->on('assets');
        $table->primary(['user_id', 'asset_id']);
        $table->decimal('amount');
        $table->timestamps();
    });
}

My POST form structure:

<div id="form" class="form">
    <form action="{{ route('home.store') }}" method="POST" novalidate>
      @csrf
        <label for="asset_id">Add Asset</label>
        <select class="form-control" id="asset_id" name="asset_id">
        @foreach($assets as $asset)
          <option value="{{$asset->id}}">{{$asset->symbol}} {{$asset->name}}</option>
          @endforeach
        </select>
      </div>
          @error('asset_id')
            <div style="color:red;">{{ $message }}</div>
          @enderror
        </div>
        <div class="form-group mb-4">
          <label for="amount">Amount</label>
          <input type="number" class="form-control" id="amount" name="amount" value=''></input>
          @error('amount')
            <div style="color:red;">{{ $message }}</div>
          @enderror
        </div>
        <input type="hidden" name="user_id" value="{{ Auth::user()->id }}">
        <button type="submit" class="btn btn-dark">Save</button>
        </form>
</div>

Controller Logic:

public function store(Request $request){

    $validAsset= $this->validate($request,[
        'amount' => 'required|numeric',
        'asset_id' => 'required',
        'user_id' => 'required'
    ]);
    
    $user = User::findOrFail(1);
    $user->assets()->attach($validAsset, [
        'amount'=> $validAsset['amount'],
        'asset_id'=> $validAsset['asset_id'],
        'user_id' => $validAsset['user_id']
    ]);

The error message I encountered:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '5-3' for key 'PRIMARY

insert into `asset_user` (`amount`, `asset_id`, `user_id`) values (7, 3, 5), (7, 3, 5), (7, 3, 5)

I am puzzled by why it is trying to store all three values in all three columns. Any insights would be appreciated!

Answer №1

To replace the attach method, you can utilize the sync method by following this syntax:

$user->assets()->sync($request->asset_id[], ['amount'=> $request->amount]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Minimize the number of HTTP requests by including CSS and JS files in PHP

I've been considering a method to reduce the number of HTTP requests made when loading a page by minimizing the amount of downloaded files, while still keeping separate files on the server. The thought process is as follows: <!DOCTYPE html> &l ...

Leveraging mod_rewrite in conjunction with CodeIgniter on Nearly Free Speech hosting platform

I must confess that I am quite inexperienced when it comes to .htaccess and server-related matters in general. Recently, I developed a website locally using Wamp and implemented a .htaccess file which I stumbled upon through online research. <IfModule ...

Fortified CakePHP: Defeating SQL Injection in Validation

I recently added a plugin called "SQL Inject Me" to my Firefox browser and decided to test it on my Cakephp website. To my surprise, the plugin was able to inject several blank user accounts, some with passwords and some without. This is strange because I ...

What are the steps for creating an nginx http cache file from scratch?

Is there a way to create nginx http cache files using PHP? The file structure should look like this: {bytecode} KEY: {cache_key} {bytecode}{http_headers} {body} I'm wondering how we can generate the {bytecode} placeholders? ...

Unable to transmit HTML emails

I've been encountering an issue while trying to send HTML emails using Gmail SMTP from CI. It seems that my emails are being rejected if they contain any tables. Interestingly, there is no error message provided; the emails simply do not show up in my ...

Eliminating empty elements in json documents within a MongoDB database

Working with php and MongoDB, the library I am using automatically generates code for mongodb calls, acting as an ODM layer. However, when dealing with embedded documents in the parent document, the library utilizes the $unset function. According to the D ...

Blank Vue Page Generated by Laravel Mix

While attempting to run npm run dev or npm run production, I encountered an error stating that the Vue file did not have loaders defined. To resolve this issue, I turned to this helpful resource: Compillation problem of extensions in vuejs I made use o ...

When Ajax attempts to run a PHP page, it redirects me to a different page

My goal is to create a live chat feature using PHP, MySQL, and AJAX. I have almost got it working perfectly, but I'm stuck on how to submit the chat message without refreshing the page. I have a PHP page called sendchat.php that takes input data and s ...

Unable to access PHP cookie information

I attempted to establish a PHP cookie by utilizing the code setcookie('usrid', $user_id, time()+3600); After inspecting this in the browser, the cookie was successfully created with the correct value assigned to the variable. However, I encounte ...

Send an array of data from the view to the Controller in CodeIgniter

I have been searching for a solution to this question. However, for some reason, my code is not functioning properly. Here is what I want to achieve: Data Array -> ajax post -> codeigniter controller(save data in DB and redirect to another page) ...

Bringing PHP Back into the World of Ajax

I created a form for users to upload new avatars and now I am experimenting with using AJAX to display error messages on the same page if any occur. However, my current issue is that the AJAX call is not receiving any response from the PHP file it's c ...

Unexpected restarts are occurring in a lengthy PHP script

I have a PHP script that I execute using the $.ajax() Javascript function: $.ajax({ type: "POST", url: "/myscript.php", data: $("#my-form").serialize() }); Details of myscript.php class myclass{ public function __construct(){ $i ...

What is causing the echo PHP output to be missing the space after the first word when viewed in MS Edge?

Whenever I execute the php script, the space gets automatically removed from the string that is printed using echo. I attempted to use echo in another place and noticed that the space remains intact. It's just in this specific case that the space dis ...

Having difficulty saving data in database using Ajax request from a Chrome extension

I am currently working on an extension that captures the page URL and saves it in a database once the user clicks the submit button. However, I have encountered a roadblock and believe there might be a missing piece in the extension setup that I cannot pi ...

Tips on incorporating express-mysql-session in a TypeScript project

I'm experimenting with using express-session and express-mysql-session in a Typescript project. Here's the relevant snippet of my code: import * as express from "express"; import * as expressSession from "express-session"; import * as expressMyS ...

What is the best way to obtain the complete URL including the # symbol in PHP?

Currently, I am implementing AngularJS routing alongside php which results in my URLs appearing as http://localhost/admin/home#/categories However, the issue arises when attempting to retrieve the full URL as it only returns /admin/home. I have tried ut ...

Trouble with $http response not appearing in AngularJS application

Currently, I am in the process of developing an angularjs application and encountering a challenging issue with setting up the $http connection to a php file. The header is displaying a response that I echoed from php. Nevertheless, two key problems persis ...

PHP Instant Chat Improvements

I am in the process of developing a messaging system that consists of the following components: A form that allows users to send messages, with PHP handling the insertion of data into a MySQL Table named userMessages upon submission. A PHP page that ...

Removing HTTPS from iframe in Zend 2

I'm having an issue with embedding an iframe in a Zend 2 view. No matter what I try, the frame is always displayed using http instead of https. I attempted to use the path in this way: echo '<iframe src="/path/to/iframe.php">'; and ...

I'm having trouble connecting to port 3000 on my Docker container from the browser

I have dockerized my application using Laravel, Nginx, and MySQL. Below are the docker-compose file and Dockerfiles used: docker-compose.yaml version: '3.8' services: # Application app: container_name: app build: context: . ...