Search code examples
laravellaravel-5.3

How do i get the primary key of a form value from the database in Laravel


Laravel 5.3

I've 3 tables [Form] - [Code_F] and [Code_R] and i have a form at the front end that ask user for 'name', 'email', 'mobile', 'age', 'code_f', 'code_r', I need to be able to add the primary key of both the 'code_f' and 'code_r' in the form table instead of the user submitted codes.

I don't want to have a select box for the user to select codes but i instead want them to write the codes they have and then i want to save them into the table FORM under code_f and code_r with their respective primary keys instead of the full value.

Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Form extends Model {

    protected $table = 'form';
    public $timestamps = true;
    protected $fillable = array('name', 'email', 'mobile', 'age', 'code_f', 'code_r');

    public function Code_F()
    {
        return $this->belongsTo('App\Code_F');
    }

    public function Code_R()
    {
        return $this->belongsTo('App\Code_R');
    }
}

Controller

    $form = new Form;
    $form->name = $request->name;
    $form->email = $request->email;
    $form->mobile = $request->mobile;
    $form->code_f = $request->code_f;
    $form->code_r = $request->code_r;
    $form->save();

Table Form

id,name,email,mobile,age,code_f,code_r

Table Code_F

id,code

Table Code_R

id,code

UPDATE: Codes are already stored in the table Code_F and Code_R and they are all numeric


Solution

  • If you are passing id of Code_f and Code_r in your request. Then you should be able to retrieve it from database like this, keeping in mind, you already know the key name (as in this case it is id)

    $code_f = Code_F::find($request->code_f);
    $code_r = Code_F::find($request->code_r);
    

    you can access the model in your save code. as $code_f->id | $code_r->id

    Updated

    I read your question again stated that you are passing codes in the request and you want to retrieve the relevant id. So, here is the drill

    $code_f = Code_F::where('code', $request->code_f)->first(); // will get you the 1st record if there are more than one
    $code_r = Code_R::where('code', $request->code_r)->first();