Popular column with created id + date/time

Asked

Viewed 39 times

1

I have a column with the name "code". Is it possible to complete it using the same method as the form? If yes, how can I implement this in my code.

Method that receives the form and inserts it into the bank.

    public function insert(ManifestationFormRequest $request)
{

    //armazena form em dataForm
    $dataForm = $request->except('_token');

    //Insere Formulário no Banco
    $insert = $this->manifestation->insert($dataForm);

    //verifica se existe arquivo e se é válido
    if($request->hasFile('upload') && $request->file('upload')->isValid())
    {
        //Define default para variavel que vai conter nome do arquivo.
        $fileName = null;

        //Define nome aleatorio baseado no timestamp atual.
        $name = uniqid(date('dmYHis'));

        //Pega extensao do arquivo original e armazena em $ext.
        $ext = $request->upload->getClientOriginalExtension();

        //Define nome do arquivo + extensão.
        $fileName = "{$name}.{$ext}";

        //Armazena arquivo em Storage/app/uploads e renomeia.
        $upload = $request->upload->storeAs('uploads', $fileName);
    }

    Alert::success('Enviado...', 'Obrigado pela sua contribuição');
    return redirect()->route('index');
}

Migrate

Schema::create('manifestations', function (Blueprint $table) {
        $table->increments('id');
        $table->string('code', 64)->nullable();
        $table->string('name', 64);
        $table->string('email', 100);
        $table->string('rg', 20)->nullable();
        $table->string('cpf', 14)->nullable();
        $table->string('address', 150);
        $table->string('cep', 10);
        $table->string('city', 36);
        $table->string('state', 8);
        $table->string('phone', 16);
        $table->string('fax', 16)->nullable();
        $table->integer('FK_cat_id')->unsigned();
        $table->string('upload')->nullable();
        $table->string('manifestation', 800);
        $table->enum('response', [
                                    'Email',
                                    'Telefone',
                                    'Fax',
                                    'Não Informado'
                                ]);
        $table->timestamps();
  • Code column where?

  • Oops! Updated with my migrate.

  • $dataForm['code'] ='value' this solves if it is a manual fill

  • $code = hexdec(uniqid()); returns a decimal value with 13 digits. I want the newly created ID concatenating with $code entered in the code field of the same record. ps: sorry if I wasn’t clear

  • Take the result of the Insert and assign the value to the code the way you want and call the save() method. Example: $Insert->code = $code; $Insert->save();

  • What I want to put together is increments('id'); with $code and put the result in the field code ta table.

  • 1

    You need to read the documentation, do this... I created a minimal example in response take a look

  • 1

    Thank you so much for the effort @Virgilionovic. I have been reading, but I haven’t been able to subtract very well what I need. I will analyze your response and make the implementation. Again my thanks!

Show 3 more comments

2 answers

1


By comments and with a simple option you can do as follows after this code just below add:

//Insere Formulário no Banco
$insert = $this->manifestation->insert($dataForm);
if ($insert) // se for inserido com êxito você já pode utilizar no modo atualização
{
    //Passa o valor ao campo code
    $insert->code = hexdec(uniqid()).$insert->id;
    //Salve a alteração
    $insert->save();
}
//Continue o código normalmente

There is also another option that is to do this with Note that in its documentation explains which may be used in the following events:

  • Retrieved
  • Creating and Created
  • Updating and Updated
  • Saving and Saved
  • Deleting and Deleted
  • Restoring and Restored

that by termination ing the event has not yet occurred, and ted that the event has already occurred and other modifications can be made, which in your case the corresponding event is created, I mean, you’ve already created the registry, so you have access to id bank-generated.

Inside the folder app create a folder named after Observers and within that folder create a file as follows:

<?php namespace App\Observers;

use App\Manifestation; // model

class Manifestation
{
    public function created(Manifestation $manifestation)
    {
        $manifestation->code = hexdec(uniqid()).$manifestation->id;
        $manifestation->save();
    }
}

then log in app\Providers\AppServiceProvider.php and add in the method boot the observer that was created:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Manifestation;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Manifestation::observe(ManifestationObserver::class);
    }
}

after that, every time a record is inserted in the event it executes this modification and changes the code value.

You can only take the id inserted right after it is generated, so it has to be in the editing mode of that record.

References:

  • 1

    It worked out here, Valew!

-2

First of all you can merge the request by adding the field.

$request->merge(['code' => $valor_que_quiser]);
$dataForm = $request->except('_token');
...

Give a dd($request->all()) after the merge and you will see that the code will be part of the form data.

At you;

Browser other questions tagged

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