How to return a collection of objects via ajax?

Asked

Viewed 613 times

1

I created this function in my Controller to return a list of employees in my ajax request, but it is not returning anything.

public function getFuncionarios(Request $request){
    if($info = Funcionario::where('id_empresa', $request->get('empresa'))){
         return response()->json($info);
    }else{
         return 'error';
    }
}

inserir a descrição da imagem aqui

When I return the direct variable does not work either.

return $info;

inserir a descrição da imagem aqui

But if I put the where to return only 1 record works.

$info = Funcionario::where('id_empresa', $request->get('empresa'))->first()

inserir a descrição da imagem aqui

What can it be? What would be the right way to get the result I need? This list of employees would be to feed a <select>.

2 answers

2

I went soft... just put the get in the end.

if($info = Funcionario::where('id_empresa', $request->get('empresa'))->get()){
    return $info;
}

1


To return a collection of objects, it can also be done as follows:

public function getFuncionarios(Request $request){

      $funcionarios = Funcionario::whereEmpresa($request->empresa)->get();
      if (!$funcionarios){
           return response()->json(['error' => 'Nenhum funcionário foi encontrado.']);
      }
      return response()->json($funcionarios);
}

to return a specific object:

public function getFuncionaio($id){

          $funcionario = Funcionario::find($id);

          return response()->json($funcionario);
    }
  • 1

    very good also @Miguelbatista, only used in the case the WhereIdCompany to be according to the column name on my table and worked perfectly.

Browser other questions tagged

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