Home > Software engineering >  Laravel appended attribute blocking AJAX query
Laravel appended attribute blocking AJAX query

Time:12-07

I have a model called OrdenesTrabajo. I have an appended field called 'show_personal' like so:

    protected $appends = [
      'show_personal', 
    ];
    public function getShowPersonalAttribute() {
      $data = [];      
      $arrPersonal =  json_decode($this->personal);
      if($arrPersonal) {
        foreach ($arrPersonal as $key => $value) {
            $data[] = Personal::find($value);
        }      
      }
      return $data;
    }

The appended field causes no problem when used in a Controller which redirects to a view. But the problem comes when I have to consult the OrdenesTrabajo model using AJAX calling a controller action, to make it work in the API controller method I have to add ->makeHidden('show_personal') because it won't load, it just keeps loading until it reaches a timeout with message: No data found for resource with given identifier. Making the appended field hidden makes the ajax query work, so I assume it's something in the appended field that's causing the problem here. It's not an option to make it hidden because I need the data.

I've also tried making the appended field hidden in the model, and making it visible when I need it but it keeps doing the same thing (loading the ajax query until timeout).

Extra info: I'm using Laravel 5.8 Thanks in advance, my apologies for any grammar mistakes.

CodePudding user response:

So I fixed it, thanks to Tim and msmahon who very much accurately pointed out my problem, it was a loop between two appended fields, both in OrdenesTrabajo model and Personal model. In Personal model I had:

    protected $appends= [
      'show_orden_trabajo', 
    ];

    public function getShowOrdenTrabajoAttribute() {
      $data = [];
      $arrOT = OrdenesTrabajo::All();
      foreach ($arrOT as $key => $value) {
        $arrPersonal = json_decode($value->personal);
        if($arrPersonal) {
          if(in_array($this->id, $arrPersonal)) {
            $data[] = $value;
          }
        }
      }
      return $data;      
    }    

so, it was appending > looping > appending > looping as Tim said. My solution was to make the show_orden_trabajo field in Personal model hidden instead of appends, and that field was used just once so when I need it I just make it visible like so:

$per = Personal::find($id)->makeVisible('show_orden_trabajo');

The original problem is that I should've had a relationship between these two models. But this made the trick, just hope in the future I don't need both fields when calling via API. Thank you both for your answers

  • Related