Is the writing of that function correct?

Asked

Viewed 45 times

0

I made this function so that it would take a js request and when inserting the name of a category, give a select in the database, check if the name already exists and if it returns 0 in Count, it will save.

It’s recording, but when I enter the same name, it still doesn’t respect the condition. Can anyone tell me why?

 public function store(Request $request)
    {

    try{

            $compara = DB::select("SELECT nome FROM categorias WHERE nome = '.$request->nome.'");


            if(count($compara) == 0)
            {
               $categoria = new Categoria();

               $categoria->fill($request->json()->all());
               $categoria->save();

               return response()->json($categoria, 201); //201 - created 
            }

        }

    catch(\Exception $ex){
        return response()->json(["error"=>$ex->getMessage() . ' on line: ' . $ex->getLine()], 500);
    }
}
  • It worked Carlos ? my answer?

1 answer

0

The DB::select is most used to return array values as you need to check if you have already registered an item by name use DB::table with where and finally the method calls the method count() as follows:

$count = DB::table('categorias')->where('nome',100)->count();

Example in the code:

public function store(Request $request)
{
    try
    {
        $count = DB::table('categorias')
                ->where('nome',$request->nome)
                ->count();  
        if($count == 0)
        {
           $categoria = new Categoria();
           $categoria->fill($request->json()->all());
           $categoria->save();
           return response()->json($categoria, 201); //201 - created 
        }

    }
    catch(\Exception $ex){
        return response()->json(
            ["error"=>$ex->getMessage().' on line: '.$ex->getLine()], 
                500
        );
    }
}

References:

Browser other questions tagged

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