Could you point why this Laravel's method doesn't correctly save a new  needed column?

Eduardo Fuerte
Eduardo Fuerte used Ask the Experts™
on
Hi Experts

Could you point why this Laravel's method doesn't correctly save a new  needed column?

<?php

//  The method signature have to receive one more parameter:    $cnpj_grupo
    private function gravarRevenda($codigoFilial, $divisaoRevenda, $tamanhoRevenda, $razaoSocial, $cnpj,        $cnpj_grupo,      $gerente, $consultor){
       
   // Previous method call 
    //private function gravarRevenda($codigoFilial, $divisaoRevenda, $tamanhoRevenda, $razaoSocial, $cnpj, $gerente, $consultor){
     

      $hierarquia = Hierarquia::where('identificador',$divisaoRevenda)->first();
      $tamanho_revenda = TamanhoRevenda::where('identificador',$tamanhoRevenda)->first();
      $tipoparticipante = Tipoparticipante::where('identificador','REVENDA')->first();
      $revenda = User::where('login',$cnpj)->first();

      if (empty($revenda)){
          $revenda = new User();
          $revenda->login=$cnpj;
          $revenda->dataNascimento='1980-01-01';
          $revenda->tipoparticipante_id=$tipoparticipante->id;
          $revenda->statusparticipante_id=3;
          $revenda->sexo_id=3;
          $revenda->created_at=Carbon::now();   
      }

      if($codigoFilial != null && $codigoFilial != '')
        $revenda->numero_filial=$codigoFilial;

      $revenda->name=$razaoSocial;
      
      $revenda->cnpj=$cnpj;
      
      // EF Jan 2020
      file_put_contents('debug.log', 'CNPJ Grupo gravarRevenda =  '.$cnpj_grupo.PHP_EOL, FILE_APPEND);
      
	  //  *******  HERE THE METHOD PARAMETER IS CORRECTLY RECEIVED *********
	  //CNPJ Grupo gravarRevenda =  64914475000176
	  //
      
    // ***********  AND SET ********************
      $revenda->cnpj_grupo=$cnpj_grupo;
      //--------------------------------
      
      $revenda->gerente_id=$gerente->id;
      $revenda->consultor_id=$consultor->id;
      $revenda->hierarquia_id=$hierarquia->id;
      $revenda->tamanho_revenda_id=$tamanho_revenda->id;
      $revenda->updated_at=Carbon::now();
      
      
      file_put_contents('debug.log', $revenda, FILE_APPEND);
	  
	  /*
	  // json obtained  --- IT HAS THE NEW PARAMETER (cnpj_grupo)
	  {
		"login": "41567664000114",
		"dataNascimento": "1980-01-01",
		"tipoparticipante_id": 3,
		"statusparticipante_id": 3,
		"sexo_id": 3,
		"created_at": "2020-01-14 15:14:24",
		"numero_filial": "1",
		"name": "Revenda Pequena do BrasilXXXXX",
		"cnpj": "41567664000114",
		"cnpj_grupo": "99378792000108",
		"gerente_id": 2879,
		"consultor_id": 2880,
		"hierarquia_id": 3,
		"tamanho_revenda_id": 1,
		"updated_at": "2020-01-14 15:14:24"
	}
	 */
	
	  //--------------------------------
      
      // Laravel model method to save data
      $revenda->save();
    }
	
?>

Open in new window


But after saving the column CNPJ_GRUPO at the table USER isn't filled.

$revenda = new User();

The User class:

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

use App\Notifications\RedefinirSenha;

class User extends Authenticatable
{
    use HasApiTokens,Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','statusparticipante_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function firstname(){
      $name = $this->name;
      $array = explode(' ',$name);
      if(count($array)>0){
        return $array[0];
      } else {
        return $name;
      }
    }

    /**
     * Send the password reset notification.
     *
     * @param  string  $token
     * @return void
     */
    public function sendPasswordResetNotification($token)
    {
        $this->notify(new RedefinirSenha($token,$this->email, $this->statusparticipante_id, $this->name));
    }

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

    public function filhos(){
      return $this->hasMany('App\User','pai_id');
    }

    public function familiares(){
      return $this->hasMany('App\Models\RevendaFamiliar','user_id');
    }

    public function consultor(){
      return $this->belongsTo('App\User','consultor_id');
    }

    public function gerente(){
      return $this->belongsTo('App\User','gerente_id');
    }

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

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

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

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

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

    public function scopePerfil($query,$value){
      if ($value===''){
        return $query;
      } else {
        return $query->where('tipoparticipante_id',$value);
      }
    }

    public function scopeStatus($query,$value){
      if ($value===''){
        return $query;
      } else {
        return $query->where('statusparticipante_id',$value);
      }
    }

    public function scopeStatuses($query,$value){
      if ($value===''){
        return $query;
      } else {
        return $query->whereIn('statusparticipante_id',$value);
      }
    }

    public function scopeLogin($query, $value){
      if ($value===''){
        return $query;
      } else {
        return $query->where('login','like','%'.$value.'%');
      }
    }

    public function scopeNome($query, $value){
      if ($value===''){
        return $query;
      } else {
        return $query->where('name','like','%'.$value.'%');
      }
    }

    public function scopeCPF($query, $value){
      if ($value===''){
        return $query;
      } else {
        return $query->where('cpf',$value);
      }
    }

    public function scopeCnpj($query,$value){
      if ($value===''){
        return $query;
      } else {
        return $query->where('cnpj',$value);
      }
    }
    
    // EF Jan/2020 C1T191    CNPJ Grupo
      public function scopeCnpj_Grupo($query,$value){
      if ($value===''){
        return $query;
      } else {
        return $query->where('cnpj_grupo',$value);
      }
    }
    //----------------------
    
    
    

    public function scopeNivel($query,$value){
      if (empty($value)){
        return $query;
      } else {
        $result = Models\Hierarquia::to_array($value);
        return $query->whereIn('hierarquia_id',$result);
      }
    }

    public function scopeConsultor($query,$value){
      if(empty($value)){
        return $query;
      } else {
        return $query->where('consultor_id',$value);
      }
    }

    public function scopeGerente($query,$value){
      if(empty($value)){
        return $query;
      } else {
        return $query->where('gerente_id',$value);
      }
    }

    public function scopeHierarquia($query,$value){
      if(empty($value)){
        return $query;
      } else {
        return $query->where('hierarquia_id',$value);
      }
    }

    public function listarRevendasPorPerfil($user_id){

      $user = User::find($user_id);

      return User
        ::where('tipoparticipante_id', \DB::raw(3))  
        ->where(function($query) use ($user){
          switch($user->tipoparticipante_id){
            case 5: $query->where('gerente_id', \DB::raw($user->id)); break;
            case 6: $query->where('consultor_id', \DB::raw($user->id)); break;
            default: break;
          };
        })
        ->orderBy(\DB::raw('trim(name)'))
        ->get();
    }
}

Open in new window


I don't know if Laravel demands another adjustments to correctly runs this save method with the new column.

Thanks in advance
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Hey Eduardo,

Have you added the new column to your DB Migrations and ran the artisan migrate. If you don't do that, then it's likely that your Table doesn't have the new column, so it can't save the User.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi Chris

What I have already done is to run this:

php artisan make:migration add_cnpj_grupo_column_to_user_table --table=users

php artisan migrate

Another file is generated were I configured the new column...

But let me better check and return....
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
From what you've just said, you have the order slightly wrong.

Step 1: php artisan make:migration add_cnpj_grupo_column_to_user_table --table=users
Step 2: Edit the newly created migration file and add in the Alter Table code to add your new column
Step 3: run php artisan migrate
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Repeated the operation:

img005
And run, with errors,

img006
Maybe I did some mistakes before, since this file that I configured out again, just now:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddCnpjGrupoColumnToUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('cnpj_grupo',14)->nullable()->after('cnpj');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
}

Open in new window


Had been lost.

So I eliminated the column cnpj_grupo from the table users and run it again:
Img_EE_007_14012020.png
Now it's ok....

And here is the file
img008
 Is it sufficient?
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Sorry, I didn't see your last interaction...

But it looks we are aligned. I'm going to check it now...
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Still not ok...

This was sent to the save method:

{
      "login": "75309639000152",
      "dataNascimento": "1980-01-01",
      "tipoparticipante_id": 3,
      "statusparticipante_id": 3,
      "sexo_id": 3,
      "created_at": "2020-01-14 17:23:47",
      "numero_filial": "1",
      "name": "Revenda Pequena do Brasil",
      "cnpj": "75309639000152",
      "cnpj_grupo": "87595344000179",
      "gerente_id": 2888,
      "consultor_id": 2889,
      "hierarquia_id": 3,
      "tamanho_revenda_id": 1,
      "updated_at": "2020-01-14 17:23:47"
}

But it was not saved...img009
And wrost, the cnpj column that previously exists since table creation is not filled also....

Any other configuration is needed?
Eduardo FuerteDeveloper and Analyst

Author

Commented:
I read something about   $fillable   as the list of columns that are could be actualized...

Does it make sense here?
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Hey Eduardo,

The screenshot that you've shown doesn't really match the data that you've posted. You're doing a name search on Teste 27, but the data you show doesn't match that so you're screenshot is not showing the correct records.

The $fillable property is used for mass assignment, so in your case it's not necessary because you're manually assigning the properties. It's handy is you're using the create() method.

Do a very simple test - add a new function that manually creates a user, populates it's properties and saves it.

function TestUser() {

    $user = new User();
    $user->login = "75309639000152";
    $user->cnpj_grupo = "87595344000179";
    $user->save();

    return $user;
}

Open in new window

Make sure you've have debugging and logging on a run the function. The output to your browser should be the user you've created, with the ID and timestamps populated. If it doesn't give you that, then check your logs.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi Chris

By following your suggestion, with adaptations:

public function TestUser() {

        $user = new User();
        
        //$user->login = "75309639000152";
//        $user->cnpj_grupo = "87595344000179";
//        $user->save();
    
    
		 $user->login= "70455640000171";
         $user->dataNascimento="1980-01-01";
         $user->tipoparticipante_id=3;
         $user->statusparticipante_id=3;
         $user->sexo_id=3;
         $user->created_at="2020-01-14 17:23:47";
         $user->numero_filial="1";
         $user->name="Revenda Pequena do Brasil";
         $user->cnpj="70455640000171";
         $user->cnpj_grupo="87595344000179";
         $user->gerente_id=2890;
         $user->consultor_id=2891;
         $user->hierarquia_id=3;
         $user->tamanho_revenda_id=1;
         $user->updated_at="2020-01-14 17:23:47";
    
    
        file_put_contents('debug.log',$user, FILE_APPEND);
        
        $user->save();

        return $user;
    }

Open in new window


The column cnpj_grupo is filled:
img001
So, something in between is deviating the flow and filling the table's column lines in a different way.....
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
OK. That's a step in the right direction - you now know that the DB Table and Model are in sync, so use that method to build up your logic step by step and check the DB data at each step. It may be that re-running the migrations has sorted the problem out.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Amazingly why this similar code doesn't work, saving correctly the columns

      $revenda->cnpj=$cnpj;
      $revenda->cnpj_grupo=$cnpj_grupo;


 private function gravarRevenda($codigoFilial, $divisaoRevenda, $tamanhoRevenda, $razaoSocial, $cnpj, $cnpj_grupo, $gerente, $consultor){
        
    //private function gravarRevenda($codigoFilial, $divisaoRevenda, $tamanhoRevenda, $razaoSocial, $cnpj, $gerente, $consultor){
      $hierarquia = Hierarquia::where('identificador',$divisaoRevenda)->first();
      $tamanho_revenda = TamanhoRevenda::where('identificador',$tamanhoRevenda)->first();
      $tipoparticipante = Tipoparticipante::where('identificador','REVENDA')->first();
     
      
      // Código original
      $revenda = User::where('login',$cnpj)->first();
      //--------------------------
      
      //EF Jan 2020
      //$revenda = new User();

      if (empty($revenda)){
          $revenda = new User();
          
          file_put_contents('debug.log', 'Revenda vazia.... '.PHP_EOL, FILE_APPEND);
          
          
          $revenda->login=$cnpj;
          $revenda->dataNascimento='1980-01-01';
          $revenda->tipoparticipante_id=$tipoparticipante->id;
          $revenda->statusparticipante_id=3;
          $revenda->sexo_id=3;
          $revenda->created_at=Carbon::now();   
                
          
      }

      if($codigoFilial != null && $codigoFilial != '')
        $revenda->numero_filial=$codigoFilial;

      $revenda->name=$razaoSocial;
      
      
      $revenda->cnpj=$cnpj;
      
      // EF Jan 2020
      file_put_contents('debug.log', 'CNPJ Grupo gravarRevenda =  '.$cnpj_grupo.PHP_EOL, FILE_APPEND);
      
      
      $revenda->cnpj_grupo=$cnpj_grupo;
      //--------------------------------
      
      $revenda->gerente_id=$gerente->id;
      $revenda->consultor_id=$consultor->id;
      $revenda->hierarquia_id=$hierarquia->id;
      $revenda->tamanho_revenda_id=$tamanho_revenda->id;
      $revenda->updated_at=Carbon::now();
      
      
      file_put_contents('debug.log', $revenda, FILE_APPEND);
      
      
      $revenda->save();
    }

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Hmmm. Not sure what's going on - did you try building it up step-by-step and check the result after each step?
Eduardo FuerteDeveloper and Analyst

Author

Commented:
I'm trying to use $user instead of $revenda. But I don't know if it makes sense....
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Yes, jus before to save the data I obtained this:

{
	"login": "98446228000104",
	"dataNascimento": "1980-01-01",
	"tipoparticipante_id": 3,
	"statusparticipante_id": 3,
	"sexo_id": 3,
	"created_at": "2020-01-15 10:57:10",
	"numero_filial": "1",
	"name": "Revenda Pequena do Brasil",
	"cnpj": "98446228000104",
	"cnpj_grupo": "00722095000157",
	"gerente_id": 2898,
	"consultor_id": 2903,
	"hierarquia_id": 3,
	"tamanho_revenda_id": 1,
	"updated_at": "2020-01-15 10:57:10"
}

Open in new window




....

     file_put_contents('debug.log', $revenda, FILE_APPEND);
     
      $revenda->save();
 }

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Not really sure what else to suggest. I'd build it up piece by piece:

private function gravarRevenda($codigoFilial, $divisaoRevenda, $tamanhoRevenda, $razaoSocial, $cnpj, $cnpj_grupo, $gerente, $consultor) {

    $user = new User();
    $user->cnpj = $cnpj;
    $user->cnpj_grupo = $cnpj_grupo;
    $user->save();

}

Open in new window

Test that and see if it works. If it does, add a couple more properties and test again. Keep doing that until it fails and then you'll know what's causing the problem.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Ok, I'm going to test it now.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Sorry, Chris

The  query used to check was wrong.
img002
Eduardo FuerteDeveloper and Analyst

Author

Commented:
I must check for the resales  not by the salesman.

That's a business rule , the salesman and the resales remains at the same table: users...

And cnpj / cnpj_grupo is just filed to the resales.
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
So that looks like everything is working, yes?
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Yes. I just got to talk to someone from the company just now.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Chris

Thank you very much for your guidance.

I'm start working with Laravel and have dificulties on how to deal with.

So all the things are adressed  incorrectly to Laravel.
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
No worries Eduardo. Glad we got there in the end :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial