Laravel - Function in Controller

Asked

Viewed 1,204 times

0

I have a question regarding Laravel and a project of mine being the function that receives the information from a form in which the administrator chooses the event and the usuarios (multiple select) to generate the certificate (stored in the table certificados - columns id / id_usuario / id_evento)

public function gerar(Request $request)
{
    $id_evento = $request->id_evento;
    $id_participantes = $request->input('participantes');   

    foreach ($id_participantes as $id)
    {
        if($this->existeCertificado($id, $id_evento))
        {
            $certificado = new Certificado();

            $certificado->id_evento = $request->id_evento;
            $certificado->qualidade = $request->qualidade;
            $certificado->id_usuario = $id;
            $certificado->save();
            $pusher = App::make('pusher');

            //default pusher notification.
            //by default channel=test-channel,event=test-event
            //Here is a pusher notification example when you create 
            //a new resource in storage.
            //you can modify anything you want or use it wherever.
            $pusher->trigger('test-channel',
                             'test-event',
                            ['message' => 'Certificado $evento->titulo_evento !!']);

            return redirect('certificado')->with('status', 'Certificados gerados!');
        }
        else
        {
            return redirect('certificado')
                       ->with('status', 'Erro ao gerar alguns certificados!');
        }            
     }
}

This is the function that searches in my database if the user (id_usuario) already has some certificate in the event (id_evento):

public function existeCertificado($id, $id_evento)
{
    $existeCert = DB::table('certificados')
             ->where([['id_usuario', $id], ['id_evento', $id_evento]])
             ->get();
    if($existeCert == NULL)
    {
        return TRUE;
    } 
    else
    {
        return FALSE;
    }        
}

If the user already has a certificate in the same event, no other is generated if it has not, it is generated.

The problem is that anyway (if there is already record of the usuario in the event or if there is no) the system falls in the else (error while generating).

  • At first the code seems to be correct, already tried to give a dd() (var_dump of the Laravel) in the received variables in the function before making the query to check if they are with correct values or come empty or in array form?

  • Every time two or more participants are chosen your code will bugar ... !!! because it makes a foreach and executes a redirect it does not perform all for ... You observed this detail?

4 answers

0

public function existeCertificado($id, $id_evento)
{
    $existeCert = DB::table('certificados')
             ->where([['id_usuario', $id], ['id_evento', $id_evento]])
             ->first();

    if(is_null($existeCert))
    {
        return TRUE;
    } 
    else
    {
        return FALSE;
    }        
}

If you replace get() with first() the value will return you the value found, or a null, if not.. just take a look at the doc, I think it might be more interesting to use the Eloquent, than the query Builder so in these married, as it is doing.

It would also be nice to make the comparison using the is_null() php function, which serves exactly to inform whether a value is null or not:

is_null() php: http://php.net/manual/en/function.is-null.php
(first) - Laravel: https://laravel.com/docs/5.6/queries

0

I refactored your code and managed to wipe the 2 methods in only 1, I hope it helps you.

public function gerar(Request $request)
{
    $fields = $request->all();

    foreach ($fields['participantes'] as $value) {
        $hasEvent = Certificado::where('id_usuario', $value)->where('id_evento', $fields['id_evento'])->first();
        if ($hasEvent) {
            return redirect('certificado')->with('status', 'Erro ao gerar alguns certificados!');
        }

        $certificado = Certificado::create($fields);
        $pusher = App::make('pusher');

        // Obs.: não sei de onde você tirou essa variavel $evento pq no seu código não tem ela instanciada
        $pusher->trigger('test-channel',
                             'test-event',
                            ['message' => "Certificado {$evento->titulo_evento} !!"]); 

        return redirect('certificado')->with('status', 'Certificados gerados!');
    }
}

-1

I believe that only with the insertion of the function firstOrNew solves the problem.

        $certificado = certificado::firstOrNew(['id_evento' => $request->id_evento]);
        $certificado->id_evento = $request->id_evento;
        $certificado->qualidade = $request->qualidade;
        $certificado->id_usuario = $id;
        $certificado->save();
        $pusher = App::make('pusher');

-1

Your code is always returning TRUE by the fact that the method get() of Eloquent returns a collection and not a boolean value. That is, even if there are no records that satisfy your query the return will always be TRUE. You must check whether this collection is empty or not so that your logic makes sense.

  • 1

    In such cases it is better to use the count() in place of get().

  • I agree that the ideal is to use the count(), but my answer was the explanation of why his logic is not working.

  • For sure, I put it to help answer Gabriel and you can even edit your answer to put an example using the count(). ;)

Browser other questions tagged

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