Is the writing of this function correct?

0

I made this function so that it takes a request from js and at the time of entering the name of a category, give a select in the database, check if the name already exists and if it returns 0 in the count, it will write. >

You are recording, but when I enter the same name, it still does not 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);
    }
}
    
asked by anonymous 08.05.2018 / 16:13

1 answer

0

DB :: select is most commonly used to return% of values as you need to verify you have already registered an item by name use DB :: table with array and finally the method call method where as follows:

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

Example in 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:

08.05.2018 / 17:23