doubt with isset () laravel 5.5 function

1

I have a concern regarding the isset function, I have the following lines.

 $usuarios=usuarios::where("usuario_ad", 'danielad')->get();
            $prueba=isset($usuarios);
            dd($prueba);

With this, the query throws records to me as long as that user exists, if it does not exist then obviously it does not throw anything, my doubt, is that isset in either case throws me false, and never true. .. how can I make this work like this?

    
asked by zereft 04.01.2019 в 20:49
source

3 answers

2

First of all it is necessary to clarify to the future visitors of this question that isset() is not a function or helper of Laravel, it is a native function of PHP and exists since PHP 4.x

This function is used to determine if a variable is defined (or not) and if its value is not NULL.

When using Eloquent and its method get() , when there are no results we get something like this:

Collection {#705 ▼
  #items: []
}

As you can see, it is an empty collection, but the variable is defined and its value is not NULL, so a check with isset() will throw true .

If the idea is to deliver a false or similar when checking whether the result of a query is empty or not, findOrFail() is not the solution either, since this function throws an exception in case a model is not found for its primary key. I leave as a reference your source code:

/**
 * Find a model by its primary key or throw an exception.
 *
 * @param  mixed  $id
 * @param  array  $columns
 * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection
 *
 * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
 */
public function findOrFail($id, $columns = ['*'])
{
    $result = $this->find($id, $columns);

    if (is_array($id)) {
        if (count($result) == count(array_unique($id))) {
            return $result;
        }
    } elseif (! is_null($result)) {
        return $result;
    }

    throw (new ModelNotFoundException)->setModel(
        get_class($this->model), $id
    );
}

In this case the best solution is to use the isNotEmpty() method of collections in Eloquent, which will deliver true if the collection is not empty, and false if it is empty.

$usuarios = usuarios::whereUsuarioAd('danielad')->get();

if ($usuarios->isNotEmpty()) {
    // colección no está vacía

} else {
   // colección vacía
}

Finally, in the code that I see in the response that the same OP raises, the rules of PSR-2, the official style guide of PHP and Laravel, are NOT being followed. Please carefully review the following link: link

    
answered by 07.01.2019 в 01:59
1

We go in parts:

  • isset() will not help you determine if a user exists, what it does is to determine if a variable is defined; for example
  • $name = "Alfa";
    
    echo isset($name);
    

    The previous code returns 1, because the variable has a value assigned

  • If what you want is to return values only if the user exists, then you must use the Eloquent method find() or better yet findOrFail()
  • $data = ModelName::findOrFail($userId);
    

    If the above is true then you can use a if else to operate the query in this way

    $data = ModelName::findOrFail($userId);
    
    if($data){
      $usuarios=usuarios::where("usuario_ad", 'danielad')->get();
      return $usuarios;
    }else{
      return "Sin datos";
    }
    
        
    answered by 05.01.2019 в 00:14
    1

    This was the alternative solution.

      public function index(Request $request)
        {
    
         $registrado = \Auth::user()->tipos_usuarios_id;
         $re = \Auth::user()->id;
         $filtro = \Auth::user()->username;
    
         if($registrado == 1)
    
            {
               $request->user()->authorizeRoles(['admin']);
               $usuarios=usuarios::orderBy('id','DESC')->paginate(10);
               $usuariosOpciones =usuarios::pluck('usuario_ad', 'user_id')->unique();
               return view('usuario.index',compact('usuarios','usuariosOpciones'));
            }
            
            if($registrado == 2)
    
              {
    
                $request->user()->authorizeRoles(['referido']);
    
                $usuarios=usuarios::where("user_id", $re)->get();
              
            
    
                if($usuarios->isNotEmpty())
                {
    
                      $usuarios=usuarios::where("usuario_ad", $filtro)->paginate(10);
                      $elid=usuarios::where("usuario_ad", $filtro)->pluck('user_id')->unique();
                      $usuariosOpciones=usuarios::where('user_id', $elid)->pluck('usuario_ad', 'user_id')->unique();
                      return view('usuario.index',compact('usuarios','usuariosOpciones'));
    
                }
                else
                {
    
                      $elid=0; 
                      $usuarios=usuarios::where("usuario_ad", $filtro)->paginate(10);
                      $usuariosOpciones=usuarios::where('user_id', $elid)->pluck('usuario_ad', 'user_id')->unique();
                      return view('usuario.index',compact('usuarios','usuariosOpciones'));
    
                }
           
              }
        
    answered by 05.01.2019 в 00:59