skip to Main Content

I have the next code of my trait.

trait ObraTrait
{
   public function custo(Request $request)
   {
      $custo = array_sum($request->custo);

      if ($custo != 100.00) {
         return back()->withInput()->with(
            'danger','Custo equal to 100.00%'
         );
      }
   }
}

and my controller

public function update(UpdateObra $request, $id)
{
   $this->custo($request);
   ....
   return redirect()->route('app.obras.index')->with(
     'success','Obra Atualizada com Sucesso'
   );
}

and the answer its…

enter image description here

I want the controller stop when $custo != 100, that it’s verified in the trait and back to the same page with a mensagem.

2

Answers


  1. Modify your custo() method in the trait to throw an exception when the condition is not met, and then catch that exception in your controller.

    Trait

    trait ObraTrait
    {
        public function custo(Request $request)
        {
            $custo = array_sum($request->custo);
    
            if ($custo != 100.00) {
                throw new RuntimeException('Custo is not equal to 100.00%');
            }
        }
    }
    

    Controller

    public function update(UpdateObra $request, $id)
    {
        try {
            $this->custo($request);
            // Rest of your update logic...
            return redirect()->route('app.obras.index')
                ->with('success', 'Obra Atualizada com Sucesso');
        } catch (RuntimeException $e) {
            return back()->withInput()->with('danger', $e->getMessage());
        }
    }
    
    Login or Signup to reply.
  2. another option:

    trait ObraTrait
    {
        public function isCusto(Request $request)
        {
            return array_sum($request->custo) != 100.00;
        }
    }
    
    public function update(UpdateObra $request, $id)
    {
       if($this->isCusto($request)) {
         return back()->withInput()->with('danger','Custo equal to 100.00%');
       }
       ....
       return redirect()->route('app.obras.index')->with(
         'success','Obra Atualizada com Sucesso'
       );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search