Problems with return api in Laravel

Asked

Viewed 105 times

0

I’m riding the return of father and daughter categories through a foreach, but the return is coming in the front-end as a object and not a array and what should I do in Laravel to the front-end make it through.

ERROR Error: "Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Below is an example.

public function show($id)
{

        $arCategoria = \App\Favorito::join('categoria', 'categoria.cd_categoria', '=', 'link.cd_categoria')
        ->select('*')
        ->where('categoria.cd_categoria_pai',$id)
        ->where('link.cd_usuario',$this->token['cd_usuario'])
        ->where('link.bo_ativo',true)
            ->get();
        //montando o array para retorno
        return $this->processarCategoria($arCategoria->toArray());
    }
    public function processarCategoria($arCategoria){
        $array = array();
        $cont = 0;
        foreach($arCategoria as $key => $value){
            $array[$value['no_categoria'].'_'.$value['cd_categoria']][] = array(
                'no_link'=>$value['no_link'],
                'cd_link'=>$value['cd_link'],
                'vl_link'=>$value['vl_link'],
                'bo_ativo'=>$value['bo_ativo'],
                'link'=>$value['link']
            );
           $cont++;
        }

        return json_decode(json_encode($array), true);;
}

Return

{
    "Documentações_3": [
        {
            "no_link": "stackoverflow",
            "cd_link": 5,
            "vl_link": null,
            "bo_ativo": 1,
            "link": "https://stackoverflow.com"
        },
        {
            "no_link": "Adventures of Time",
            "cd_link": 9,
            "vl_link": null,
            "bo_ativo": 1,
            "link": "http://adventuresoftime.com.br"
        }
    ],
    "Datas comemorativas_5": [
        {
            "no_link": "Games",
            "cd_link": 10,
            "vl_link": null,
            "bo_ativo": 1,
            "link": "Games.com.br"
        }
    ]
}

Front-end

service ts.

getLinksByIdusuario(id:number):Observable<any[]> {
    return this.http.get<any[]>(`${API}/favorito/${id}`)
    .pipe(map((data: any) => data ), 
                catchError(error => { return throwError(error)})
          );
  }

Component.

ngOnInit() {


    this.id = params['id'];
    this.homeService.getLinksByIdusuario(this.id)
    .subscribe(
      categorias => {
        this.categorias = categorias
      }
    )
}

Component.html

<div class="row">
    <div *ngFor="let categoria of categorias | keyvalue">
        {{categoria.key}} 
        <div *ngFor="let cat of categoria">
            {{cat.no_link}} 
        </div>
    </div>
</div>
  • This mistake is not giving in to your Front-End???

  • @Virgilionovic, this, fron-end

  • The problem is not in PHP friend is how you treat this data in your Front has how to put the code of the Front?

  • @Virgilionovic updated my question by adding the front

  • where is the error? if you know the line where to

2 answers

0

Return the data in json

return response->json($data);

In your angular service do more the less so:

public getOne(id: number): Observable<any> {
  return this._http.get(`${this.apiUrl}/${id}`).catch((err) => this.catchError(err));
}

On your computer capture the data:

this.service.getOne().subscribe(
  (res: any) => {
    this.data = res;
  },
  (err) => {
    console.log(err);
  }
);

In html:

*ngFor="let d of data">

0

That call on the controller is a little fuzzy.. and so is the answer. This is not really an array, but a mixture of arrays, with indices with strings with spaces. I had a project where a Veloper manipulated the API for a result similar to yours, and it was a nightmare to loop the frontend. No need for these loops (With many logs will only delay the application).

Let’s keep the operation simple:

Before the controller class put:

use Response;

In the query, remove the fields you want in select (Since I don’t know what comes from each table, my suggestion is just suggestive..)

$arCategoria = \App\Favorito::join('categoria', 'categoria.cd_categoria', '=', 'link.cd_categoria')
    ->select('link.no_link','link.cd_link','link.bo_ativo','link.vl_link')
    ->where('categoria.cd_categoria_pai',$id)
    ->where('link.cd_usuario',$this->token['cd_usuario'])
    ->where('link.bo_ativo',true)
        ->get();

There is no need to manipulate the array, it can soon return the response that comes from the BD.

return Response::json($arCategoria);

The frontend looks angular. Try the following:

ngOnInit() {
    this.id = params['id'];
    this.homeService.getLinksByIdusuario(this.id)
    .subscribe(
      categorias => {
        const responseData = JSON.parse(categorias._body);
        this.categorias = responseData.data;
      }
    )
}

The loop should already work smoothly.

  • Ricardo, with this the loop will work, but will not come organized, leaving the work to the front. I have to assemble a tree logic, which is being done in the Variable in Processcategory(). Look at the example with parseCategoria https://i.imgur.com/Koe9106.png vs direct return from the database. https://i.imgur.com/Iekzspq.png . Thank you.

  • @Herick I understand, with Laravel you can also get the information out of the database immediately organized, you just have to work a little bit on Laravel’s models. In the category model, you make a relation with the links model, and then in the controller you make Links::with('Categories')->Where('id',$Something')->get(). This will return you an object similar to what you want. Take a look here: https://laravel.com/docs/5.7/eloquent-relationships

  • @Herick, if you give me the names of the models, I’ll edit my answer.

Browser other questions tagged

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