M
M
Michael2017-05-10 15:20:36
Laravel
Michael, 2017-05-10 15:20:36

How can I change the default save request to the database in Laravel?

Good day to all!
The essence of the question is this:
There is a table in the database that stores the values ​​​​of network adapters, so the "id" field was not created in the table, and the "mac" field was assigned as the key field, since the physical addresses themselves are unique.
To save the network adapter data after editing, I wrote the following function:

public function saveNic (Request $request)
    {
        $data = $request->all();
        $host = $data['host'];
        unset ($data['host']);
        $tmp= Networkcard::select(['mac', 'name', 'network', 'wol'])->where('mac',$data['mac'])->get();
        $nic=$tmp[0];
        $nic->fill($data);
        $nic->save();
        return redirect("/host/".$host);
    }

As you can see in the code, I bypassed the problem with selecting from the database as follows (if this can be improved, please tell me how).
But when saving and calling the save() method, Laravel generates a query in which the id field is considered the key field. In view of this, it reasonably tells me about the error.
cb71f757aa1d4377a6c0c6f33270533b.PNG
Please tell me how can I change the request using Laravel tools to save data, or can I add some parameters to the save () method so that the request does not look for a match by the mac field, and not by the id field?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
riot26, 2017-05-10
@MikhailBond

Add to the Networkcard model:
protected $primaryKey = 'mac';

S
Sergey Semenko, 2017-05-10
@abler98

Per model:

protected $primaryKey = 'mac';
public $incrementing = false;

And how can you code laravel like that?
Something like this can be done:
Networkcard::where('mac', $request->get('mac'))->update($request->all());
return redirect()->back(); // Думаю это подойдёт

In the model, define $fillable (fields for quick updating)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question