0

Suppose I have a table 'table' with columns: col1 and col2. I create it via migration:

public function up()
{
    Schema::create('table', function (Blueprint $table) {
        $table->increments('id');
        $table->string('col1');
        $table->string('col2');
}

Is it possible to define the following behaviour at the 'database layer'(without configuring it in the controller or model layers):

When I am inserting a new record in the table, I want the value of col2=col1, if value of col2 is not available.

example:

Table::create(['col1'=>'a']);

id col1 col2
1   a     a

Table::create(['col1'=>'a', 'col2'=>'b']);

id col1 col2
2   a     b

Hope I've explained clearly what I want to achieve... thank you in advance:)

Sergej Fomin
  • 1,822
  • 3
  • 24
  • 42

2 Answers2

0

What you are asking is dynamic default value which is a little tough to my knowledge in mySQL, why don't you check it while inserting it in controller and then place the data as in:

public function create(Request $request)
{
    $data = $request->only('col1', 'col2');
    $data['col2'] = $data['col2'] ? $data['col2'] : $data['col1'];
    $createData = Table::create($data);
    return 'Data created successfully';
}

It can be more clean an efficient. Hope this helps.

Nitish Kumar
  • 6,054
  • 21
  • 82
  • 148
0

Personally, I'd maintain that kind of logic in the controller, simply because in an MVC environment, that's where I'd go looking for it if I wanted to change it. (Predictability being a kindness to any devs that might come after you. Might not apply in this case, but a good habit.)

Still, if you're up for a bit of reading, MySQL Triggers can probably do what you have in mind, among a whole world of other things.

And just to head off one of the pitfalls, as noted in this post

[In MySQL] To check NULL values we need to use IS NULL & IS NOT NULL operator.

DevBodin
  • 163
  • 7