Laravel Create composite key for pivot table?

Asked

Viewed 73 times

-2

I would like to know how it is possible to perform validation in the 6.x Standard for composite keys ?

I am wanting to insert new data a pivot table that has many link to many with two other tables.

public function up()
{
    Schema::create('acl_cm_tecnicos', function (Blueprint $table) {
        $table->unsignedInteger('id_tecnicos');
        $table->unsignedInteger('id_cms');
        $table->primary(['id_tecnicos', 'id_cms']);
        $table->foreign('id_tecnicos')->references('id')->on('ctrl_lista_tecnicos');
        $table->foreign('id_cms')->references('id')->on('ctrl_cm_tecnicos');
    });
}

I performed tests for entering new data are ok !

But I would like to have a validation on backend, to avoid error in the application in cases of trying to enter duplicate records.

I tried to create some validations like this.

 public function store(Request $request)
 {
    //$cadAcl = $this->objAcl->create([
    //    'id_tecnicos'=>$request->id_tecnico,
    //    'id_cms'=>$request->id_cm,
    //]);

    $datatec = $this -> $request->tecnico_id;
    $datacm = $this -> $request->id_cms;

       $validacao =  $this->validate($request, [
            'id_tecnicos' => 'unique:acl_cm_tecnicos,id_tecnicos,NULL,id,id_cms'.$datacm,
            'id_cms' => 'unique:acl_cm_tecnicos,id_cms,NULL,id,id_tecnicos'.$datatec,
            
        ]
        );

        dd($validacao);

But I confess that I am a little lost by the attempts I have already made. On this last attempt I have following error in output of dd($validation);

Errorexception Undefined Property: App Http Controllers Scheduling Resource Accfticscontroller::$POST /acltecnicos HTTP/1.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8,application/Signed-exchange;v=B3;q=0.9 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,en-BR;q=0.8,en;q=0.7 Cache-Control: max-age=0 Connection: Keep-Alive Content-Length: 372 Content-Type: Multipart/form-date; Boundary=---Webkitformboundarydpbr1ikfb0ntx9du Cookie: XSRF-TOKEN=Nlnjm0zjk4njm1nzg0otq2nta1ytu0nta0zgrknza1zjfhmdu1mge1ntjmin0%3D; laravel_session=eyJpdiI6IjUrb3EzK3hBd3ZXSEtRTTFFVGswZUE9PSIsInZhbHVlIjoidjNSQ3pIM0ZOSytqMWlPZWEwS1N6VmlBZ2VRT21DRHlBNHRlOTk5cDRQaGtpTjN3bnZ5V2djeXBhb0F1WmJzVDliWncybXFOWnRqTkJcL1g2UHVMNVIyODk2aVlkdlBIdTdoQzJtbmFya3ZQd3pxQngxUTA4K3p4ZUhmMkNwR3dxIiwibWFjIjoiZDliNGJlNzQ5MmZhMWU1ODY3ZjcyYjk2ztg1nmeyzdgxogjjnmzjmwnhyzcxmzi2mzgynzdjyzgwy2uyztu4yij9 Dnt: 1 Host: 127.0.0.1:8000 Origin: http://127.0.0.1:8000 Referer: http://127.0.0.1:8000/tecnicos/980/Edit Sec-Fetch-Dest: Document Sec-Fetch-Mode: navigate Sec-Fetch-Site: same-origin Sec-Fetch-User: ?1 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) Applewebkit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 Cookie: XSRF-TOKEN=Jpfbbalpgyx59xvgtdrsgcshyyfsbaqeuik8gjts; laravel_session=zY4ITpf8RvqzZ55HJMwlKOra8QuErGbPExGDel5S

1 answer

0

You need to create a rule for this table with the command:

php > php artisan make:rule TestRule

after giving this command the code is created in: app\Rules, open the file and start your encoding:

<?php namespace App\Rules;

use App\Test;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\Request;

class TestRule implements Rule
{
    public $request;
    public $test;
    public function __construct(Request $request, Test $test)
    {
        $this->request = $request;
        $this->test = $test;
    }

    public function passes($attribute, $value)
    {
        $p1 = $this->request->input('p1');
        $p2 = $this->request->input('p2');
        $count = $this->test->where(function($query) use($p1,$p2) {
            $query->where('p1', $p1)
                ->where('p2', $p2);
        })
        ->count();
        return (int)$count === 0;
    }

    public function message()
    {
        return 'The duplicate value';
    }
}

that in its constructor Request and the class responsible for that table in the example case of that code is Test.

Within the method passes($attribute, $value) has a code that searches if the request data may be duplicated and in the method count of builder is counted if there are any items in this search.

In the code that arrives the request put this rule in the validation part:

$validator = Validator::make($request->all(), [
    'p1' => ['required', new TestRule($request, $this->model)], // regra
    'p2' => 'required',
]);

if ($validator->fails()) {
    return redirect('test')
                ->withErrors($validator)
                ->withInput();
} else {
    $this->model->create($request->except('_token'));
    return redirect('test');
}

basically, create a rule with the mentioned command, implement a verification code in the table by method passes and in the request button code please install the rule class and pass the value of your constructor.

  • Thank you very much it worked out vlw by force !!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.