mardi 4 mai 2021

what is the difference between $model properity and newFactroy method in laravel factroy

i have a question regarding why do we need to set protected $model = User::class when defining a Factory and in the model itself we need sometimes (if we did not use a convention for Factory name ) to override newFactory method to tell the model about the Factory ? why we need both of them ? why not to use $model properity only ? or newFactory() only ? why both of them ??

      class UserFactory extends Factory{
protected $model = User::class;
}

and inside the model

   public static function newFactory(){
        return UserFactory::new();
 }


via Chebli Mohamed

lundi 3 mai 2021

How to make laravel offline app through which user download from play store and it is offline

I want to make attendance management app (which is built with laravel) work offline...but I cant found out how to do it!

What i use for static files, but i am not sure exactly how to handle the dynamic side of the app.

The app uses a database which i am guessing I need to use localStorage for? (from what i have read online so far)

Im basically just looking for someone to point me in the right direction as i am struggling to find much online on setting up Laravel for use offline.

thanks for helping me.



via Chebli Mohamed

FormData jQuery AJAX Returning Null

I am trying to use FormData() for sending texts and images. It's not working

$('#saveBtn').click(function(e) {
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        var formDataEdit = new FormData();

        //formDataEdit.append('images', $('#images')[0].files[0]); // for single item
        formDataEdit.append('nameForEdit', $("input[name='nameForEdit']")
            .val());
        formDataEdit.append('codeForEdit', $('#codeForEdit').val());
        formDataEdit.append('categoriesForEdit', $('#categoriesForEdit').val());
        formDataEdit.append('stokForEdit', $('#stokForEdit').val());

        let TotalImages = $('#photoForEdit')[0].files.length; //Total Images
        let images = $('#photoForEdit')[0];
        for (let i = 0; i < TotalImages; i++) {
            formDataEdit.append('images' + i, images.files[i]);
        }
        formDataEdit.append('TotalImages', TotalImages);

        console.log(formDataEdit.get('nameForEdit')); // it's works, returning the value of name. 
        console.log(formDataEdit.append('codeForEdit', $('#codeForEdit')
            .val())); // it's not working. Returning undefined. */

        $.ajax({
            url: "products/" + id,
            method: 'PUT',
            data: formDataEdit,
            enctype: 'multipart/form-data',
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'JSON',
            async: true,
            headers: {
                'Content-Type': undefined,
            },
            xhr: function() {
                myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            success: function(result) {
                if (result.errors) {
                    $('.alert-danger').html('An error in your input fields');
                    $.each(result.errors, function(key, value) {
                        $('.alert-danger').show();
                        $('.alert-danger').append('<strong><li>' + value +
                            '</li></strong>');
                    });
                } else {
                    $('.alert-danger').hide();
                    $('.alert-success').show();
                    $('.datatable').DataTable().ajax.reload();
                    setInterval(function() {
                        $('.alert-success').hide();
                        $('#ajaxModel').hide();
                        location.reload();
                    }, 2000);
                }
            },
            error: function(response) {
                $('#codeError').text(response.responseJSON.errors.code);
                $('.alert-danger').html('An error in your input fields');
                $.each(response.errors, function(key, value) {
                    $('.alert-danger').show();
                    $('.alert-danger').append('<strong><li>' + value +
                        '</li></strong>');
                });
            }
        });
    });

Everytime I use dd($request->get('stokForEdit')) for example, it's returning null

But, when I change code to below without FormData(), it's working.

url: "products/" + id,
        method: 'PUT',
        data: {
                nameForEdit: $('#nameForEdit').val(),
                codeForEdit: $('#codeForEdit').val(),
                categoriesForEdit: $('#categoriesForEdit').val(),
                stokForEdit: $('#stokForEdit').val(),
        },
        enctype: 'multipart/form-data',
        cache: false,
        //contentType: false,
        //processData: false,
        dataType: 'JSON',
        async: true,
        headers: {
            'Content-Type': undefined,
        },
        xhr: function() {
            myXhr = $.ajaxSettings.xhr();
            return myXhr;
        },

I can't use the second way, because I need to send an images. Help me with the soultion!



via Chebli Mohamed

can't run laravel 5.7 on php8

hi guys I need help for this case I can't run laravel 5.7 on php8, when I do "php artisan serve" I got error:

thrown in /var/www/html/myProject/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 838
PHP Fatal error:  Uncaught ErrorException: Method ReflectionParameter::getClass() is deprecated in /var/www/html/myProject/vendor/laravel/framework/src/Illuminate/Container/Container.php:838

I have tried to update composer required php version form "^7.1.3" to "php": "^7.1.3|^8.0", and when I run composer update I got another error.

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel/framework[v5.7.0, ..., 5.7.x-dev] require php ^7.1.3 -> your php version (8.0.3) does not satisfy that requirement.
    - Root composer.json requires laravel/framework 5.7.* -> satisfiable by laravel/framework[v5.7.0, ..., 5.7.x-dev].

I hope any body sharing what is solution for this case



via Chebli Mohamed

how to set color warning when status "Waiting Confirmation"?

i want to make warning label for "waiting confirmation" status, the code as below :

->editColumn('status', function ($aduan) {
           $color = ($aduan->status == 'Pending') ? 'label-danger' : 'label-success';
           return '<span class="label ' . $color . '">' . $aduan->status . '</span>';
  })


via Chebli Mohamed

Laravel queues are not processing automatically until I run php artisan queue:work command

I came through multiple solutions on stack overflow but no luck. It worked fine before 1 month but now a days it is not working.

I am using Ubuntu Os and nginx server. For queue driver I used redis Here is my redis configuration in .env

BROADCAST_DRIVER=log
CACHE_DRIVER=redis
SESSION_DRIVER=file
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

I also used supervisor to monitor and here is my configuration for supervisor

[program:worker-326242]
command=php7.4 /home/forge/myapp.com/artisan queue:work redis --sleep=10 --daemon --quiet --tries=3 --env=production --queue="default"

process_name=%(program_name)s_%(process_num)02d
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=forge
numprocs=1
stdout_logfile=/home/forge/.forge/worker-326242.log

The problem is queue jobs are not executing automatically but it works when i run the command "php artisan queue:work"

Please ignore my poor english. Any help will be appriciated



via Chebli Mohamed

"Trying to access array offset on value of type bool" erro para editar cadastro

pt-BR

Olá, estou criando uma tela de edição de cadastro porém estou me deparando com o seguinte erro, achei alguns conteúdos similares aqui no fórum, porém nenhum me ajudou!

Eu uso laravel 5.8 php 7.4

"Trying to access array offset on value of type bool" Imagem do erro

EN

Hello, I am creating a registration edit screen but I am encountering the following error, I found some similar content here on the forum, but no other qualifies me!

I use laravel 5.8 php 7.4

"Trying to access array offset on value of type bool" error image

Controller:

public function editaItemBombeamento(Request $req)
{
    $dados = $req->all();
    // Bombeamento::find($dados['id_bombeamento'])->update($dados);
    // Dados do formulário.
    $dados['id_usuario'] = Auth::user()->id;
    $id_afericao  = $dados['id_afericao'];
    $bombeamentos = [];
    Bombeamento::find('id');
    for ($i = 0; $i < $dados['numero_bombas']; $i++) {
        $bombeamento['id_bombeamento'] = $dados['id_bombeamento'];
        $bombeamento['comprimento_succao'] = $dados['comprimento_succao'][$i];
        $bombeamento['diametro_succao'] = $dados['diametro_succao'][$i];
        $bombeamento['marca'] = $dados['marca'][$i];
        $bombeamento['modelo'] = $dados['modelo'][$i];
        $bombeamento['numero_rotores'] = $dados['numero_rotores'][$i];
        $bombeamento['diametro_rotor'] = $dados['diametro_rotor'][$i];
        $bombeamento['material_succao'] = $dados['material_succao'][$i];
        $bombeamento['rendimento_bomba'] = $dados['rendimento_bomba'][$i];
        $bombeamento['shutoff'] = $dados['shutoff'][$i];
        $bombeamento['rotacao'] = $dados['rotacao'][$i];
        $bombeamento['pressao_bomba'] = $dados['pressao_bomba'][$i];
        $bombeamento['tipo_motor'] = $dados['tipo_motor'][$i];
        $bombeamento['modelo_motor'] = $dados['modelo_motor'][$i];
        $bombeamento['potencia'] = $dados['potencia'][$i];
        $bombeamento['numero_motores'] = $dados['numero_motores'][$i];
        $bombeamento['chave_partida'] = $dados['chave_partida'][$i];
        $bombeamento['fator_servico'] = $dados['fator_servico'][$i];
        $bombeamento['corrente_nominal'] = $dados['corrente_nominal'][$i];
        $bombeamento['rendimento'] = $dados['rendimento'][$i];
        $bombeamento['tensao_nominal'] = $dados['tensao_nominal'][$i];
        $bombeamento['frequencia'] = $dados['frequencia'][$i];
        $bombeamento['corrente_leitura_1_fase_1'] = $dados['corrente_leitura_1_fase_1'][$i];
        $bombeamento['corrente_leitura_1_fase_2'] = $dados['corrente_leitura_1_fase_2'][$i];
        $bombeamento['corrente_leitura_1_fase_3'] = $dados['corrente_leitura_1_fase_3'][$i];
        $bombeamento['tensao_leitura_1_fase_1'] = $dados['tensao_leitura_1_fase_1'][$i];
        $bombeamento['tensao_leitura_1_fase_2'] = $dados['tensao_leitura_1_fase_2'][$i];
        $bombeamento['tensao_leitura_1_fase_3'] = $dados['tensao_leitura_1_fase_3'][$i];
        $bombeamento['corrente_leitura_2_fase_1'] = $dados['corrente_leitura_2_fase_1'][$i];
        $bombeamento['corrente_leitura_2_fase_2'] = $dados['corrente_leitura_2_fase_2'][$i];
        $bombeamento['corrente_leitura_2_fase_3'] = $dados['corrente_leitura_2_fase_3'][$i];
        $bombeamento['tensao_leitura_2_fase_1'] = $dados['tensao_leitura_2_fase_1'][$i];
        $bombeamento['tensao_leitura_2_fase_2'] = $dados['tensao_leitura_2_fase_2'][$i];
        $bombeamento['tensao_leitura_2_fase_3'] = $dados['tensao_leitura_2_fase_3'][$i];
        array_push($bombeamentos, $bombeamento);
    }
    // Inserindo os dados de bombeamento no DB.
        $transaction = false;
        $transaction = DB::transaction(function () use ($bombeamentos, $id_afericao) {
            foreach ($bombeamentos as $key => $bombeamento) {
                Bombeamento::update($bombeamento);
            }
            // Atualizando a flag de pendência na tabela de aferição
            AfericaoPivoCentral::find($id_afericao)->update(['bombeamento_pendente' => 0]);
            return true;
        });

    // Inserção de dados no DB OK.
    if ($transaction) {
        Notificacao::gerarAlert('afericao.sucesso', 'afericao.edicaoSucesso', 'info');
        return redirect()->route('status_afericao', $dados['id_afericao']);
    }
    // Problema para salvar no DB
    else {
        Notificacao::gerarAlert('afericao.erro', 'afericao.erro_processamento', 'warning');
    }
}

Foto do inicio do meu código na view

Classe

class Bombeamento extends Model{
use SoftDeletes;
protected $dates =  ['deleted_at'];
protected $fillable = [
    'id_bombeamento' , 'id_usuario', 'comprimento_succao', 'diametro_succao', 'marca', 'modelo', 'numero_rotores',
    'diametro_rotor', 'material_succao', 'rendimento_bomba', 'shutoff', 'rotacao', 'pressao_bomba',
    'tipo_motor', 'modelo_motor', 'potencia', 'numero_motores', 'chave_partida', 'fator_servico', 'corrente_nominal', 
    'rendimento', 'tensao_nominal', 'frequencia',

    'corrente_leitura_1_fase_1', 'corrente_leitura_1_fase_2', 'corrente_leitura_1_fase_3',
    'corrente_leitura_2_fase_1', 'corrente_leitura_2_fase_2', 'corrente_leitura_2_fase_3',

    'tensao_leitura_1_fase_1', 'tensao_leitura_1_fase_2', 'tensao_leitura_1_fase_3',
    'tensao_leitura_2_fase_1', 'tensao_leitura_2_fase_2', 'tensao_leitura_2_fase_3',
];


via Chebli Mohamed