What is the process for linking the foreign key value to the primary key of a separate table in Laravel?

I have set up a cproduct table in my Laravel project with 3 foreign keys. Now I want to populate this table using Postman. Can anyone guide me on how to achieve this?

This is the structure of the c_products table:

 public function up()
{
    Schema::create('c_products', function (Blueprint $table) {
        $table->bigIncrements('cproduct_id');
        $table->string('name');
        $table->string('file_path');
        $table->integer('price');
        $table->foreignId('category_id')->nullable()->constrained('p_categories');
        $table->foreignId('cactus_id')->nullable()->constrained('cacti');
        $table->foreignId('id')->nullable()->constrained('users');
        $table->timestamps();
    });
}

In my CProductController, I have written code to add data to the cproducts table:

  <?php

  namespace App\Http\Controllers;

  use Illuminate\Http\Request;
  use App\Models\CProduct;
  class CProductController extends Controller
  {
   //
   function addCProduct(Request $req)
  {
    $cproduct=new CProduct;
    $cproduct->name=$req->input('name');
    $cproduct->price=$req->input('price');
    $cproduct->color=$req->input('color');
    $cproduct->file_path=$req->file('file')->store('c_product');
    $cproduct->save();
    return $cproduct;
  }
 }

I believe I need to include the foreign key fields in the "function addCProduct". Could someone provide me with the necessary code for this?

Your assistance is greatly appreciated!

Answer №1

Display categories in a list format within your form

<select name="category_id">
  @foreach($categories as $category)
    <option value="{{ $category->id }}"> {{ $category->title }} </option>
  @endforeach
</select>

To retrieve the category id in your controller, use the following method:

function addCProduct(Request $req)
  {
    $cproduct=new CProduct;
    $cproduct->category_id=$req->input('category_id');
    $cproduct->name=$req->input('name');
    $cproduct->price=$req->input('price');
    $cproduct->color=$req->input('color');
    $cproduct->file_path=$req->file('file')->store('c_product');
    $cproduct->save();
    return $cproduct;
  }

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

What is the process for exporting data from MongoDB?

Recently, I created a web application for fun using Handlebars, Express, and Mongoose/MongoDB. This app allows users to sign up, post advertisements for others to view and respond to. All the ads are displayed on the index page, making it a shared experie ...

Using setInterval to eliminate duplicate markers from a leaflet map

I have been working on a Leaflet map project with markers. The markers' latlng data is fetched from JSON and displayed correctly. I tried using setInterval to refresh the method every 5 seconds to update the latlng positions, ensuring that old marker ...

Does the gltf loader in three.js have compatibility issues with Internet Explorer 11?

Despite the claims on the official website that gltf files should load in three.js scenes using IE11, I have been experiencing issues with the loader. Even the examples provided by three.js fail to work on Internet Explorer when it comes to loading gltf fi ...

What is the best approach for implementing form validation that is driven by directives in AngularJS?

Currently, I am working on creating a registration form using AngularJS. I need to use the same form in four different sections. To achieve this, I have created a common form within a single HTML page as shown below: <div> <div> < ...

What is the significance of the -infinity value in the JavaScript console?

Recently, while learning JavaScript ES6, I came across a strange result of -infinity on my console when running the following code: let numeros = [1, 5, 10, 20, 100, 234]; let max = Math.max.apply(numeros); console.log(max); What does this ...

How do I determine which radio button is currently selected within my Angular2 application?

In my HTML, I have the following radio buttons: <div class="col-lg-4" id="radioButtons"> <form action=""> <fieldset id="capacity"> <legend>capacity</legend> <label for="input-ao">< ...

What could be the reason for the Azure server sending a Bad Request response?

My NodeJS application is currently hosted on Azure server and all APIs are functioning correctly, providing the expected responses. The issue arises when trying to run a GET API like the following: https://demoapp.azurewebsites.net/mymenu?userId=piyush.d ...

Converting a JSONArray object into jQuery format

Within my Java code, there exists a JSONArray object labeled colorList that stores a collection of different colors. For example, the array may be constructed like so: ["Red", "Yellow", "Blue"] I am seeking guidance on how to transfer this information ...

Transmit an array using a GET Request

I am currently working on a project where I need to make a GET request from JavaScript to Python and pass a 2D array. Here is an example of the array: [["one", "two"],["foo", "bar"]] However, I am facing issues with passing this array correctly. In my Ja ...

Conceal DIV containers during the loading of the page, and reveal them only upon the selection of Radio Buttons

In my user interface, I have implemented three radio buttons labeled as "Easy," "Medium," and "Hard." Each button is assigned to a distinct Javascript function that manipulates the visibility of corresponding div elements. The main purpose behind this setu ...

Is it possible to reverse engineer a UI by starting from its current state and debugging backwards?

When it comes to web development, users often provide screenshots of their "invalid state". Using React, I had a thought about debugging in a different way: starting from the current state: A user sends us a screenshot of an invalid UI state. We use dev ...

The installed NPM package does not contain the necessary TypeScript compiled JS files and declaration files

I have recently released a TypeScript library on NPM. The GitHub repository's dist (Link to Repository Folder) directory includes all compiled JavaScript and d.ts files. However, after running npm i <my_package>, the resulting module contains on ...

Difficulty fetching css files on handlebars (express API)

Recently, I encountered an issue where the CSS styles were not being applied to my HBS code despite several attempts. The structure of my service is as follows: Service Controllers Models public css styles.css Routers Views index.hbs app.js pac ...

Link that updates periodically linked to an image

My goal is to have a URL change on a timer that is linked to an image. For example, after 10 seconds, I want the URL attached to the image to change without changing the actual image itself. I've been trying to figure out how to modify this code, but ...

My script is unable to access the session variable

Two $_SESSION variables seem to be inaccessible in any script on my page, yet I can confirm their existence in the PHP code of the same page by using echo to display their values. When trying to display these $_SESSION variables in jQuery using the code b ...

Tips for integrating new channels and categories using a Discord bot

Hey there! I'm trying to add channels and categories, but I can't seem to get the function ".createChannel" working. The console keeps telling me that the function doesn't exist. I've been referencing the documentation at https://discor ...

How can I retrieve the 'GET' parameter in a controller using Laravel?

I am having trouble passing a parameter in the URL and accessing it in the controller class. // .vue class let url = "/getslots/{$day}"; This is my routing file (web.php): Route::get('/getslots/{day}', 'SlotController@getDay'); Here ...

Concealed Content Within Drawer Navigation

When using the Material UI permanent drawer component in different pages, I encountered an issue where the main content was getting hidden behind the drawer's toolbar and sidebar. I am unsure how to fix this problem. It seems like a styling issue, bu ...

Error: The function "execute" has not been declared

Hey there! I've created a Discord bot that is meant to check the status of a Minecraft server, but I'm encountering an issue with the embed. It's showing this error: UnhandledPromiseRejectionWarning: ReferenceError: execute is not defined. ...

Determine the size of a pixel by analyzing its zoom percentage

I am facing a technical challenge that involves coding and math, but my skills are better suited to the former than the latter! My task involves working with a div that is 500 pixels wide and utilizing Jquery. To begin, I will determine the width of the ...