skip to Main Content

I am creating a virtual shop website and I’m trying to do a Product register page.

Some of the fields from the product form are not required, so I need a way to make my Controller only add the columns that match the received inputs.

I’ve tried doing it with an associative array, where ["column-name"=>"column-input"], but when I try to run the query, Laravel considers all of the array rows as different insert queries with only the first column of the DB, like this:

SQL: insert into `produtos` (`nome`) values (Smartphone Samsung Galaxy A34 128GB), (Marca:Samsung Modelo:Galaxy), (1),[...]

The desired behaviour would be along the lines of:

SQL: insert into `produtos` (`nome`,`descricao`,`ativado`,[...]) values ("Smartphone Samsung Galaxy A34 128GB","Marca:Samsung Modelo:Galaxy", 1,[...])

Here is the Controller code:

    public function insert($post){
        $campos = Array();   // fields array
        foreach($post as $key=>$value){
            array_push($campos,[$key=>$value]);
        }

        $query = DB::table('produtos')->insert($campos);
        return $campos['url'];
    }

Is there any way I can achieve that?

2

Answers


  1. To insert data into the produtos table after validating the input, you can use Laravel validation in combination with the DB::table insert method.

    public function insert($post){
      $campos = Array();    
      foreach($post as $key=>$value){
          array_push($campos,[$key=>$value]);
      }
    
      $data = $this->validateForm(new Request($campos));
      DB::table('produtos')->insert($data);
      return $campos['url'];
    }
    

    the validation function will be like below. update the fields with necessary validations that laravel has provided. to know more about validation laravel doc https://laravel.com/docs/10.x/validation#working-with-validated-input

        public function validateForm(Request $request)
        {
            return $this->validate($request, [
                'nome'           => ["required"],
                'descricao'      => ["required"],
                'ativado'        => ["required"],
            ]);
        }
    
    Login or Signup to reply.
  2. The create method in Laravel’s Eloquent ORM is a convenient way to create a new model instance and persist it to the database

    Produtos::create($campos);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search