[Vuejs]-Vue.js and Laravel difference return json and resource

1👍

The difference is that the first method triggers the model method toArray.

<?php

class Message 
{
   public function getExcerptAttribube() {
     return '...'; // strip HTML, etc ... 
   }

   public function toArray() {
      return [
         'id' => $this->id,
         'title' => $this->title,
      ]
   }
}

This makes it easy to programmatically hide, casts or append properties when turning models to JSON.

This can of course also be done with mutators like $appends, $hidden, $casts, $with.

Eloquent mutators: https://laravel.com/docs/5.6/eloquent-mutators#array-and-json-casting

The seconds method with a resource allows to move that logic to a separate object.

<?php

class MessageResource extends JsonResource
   public function toArray($request) {
      $message = $this->resource;
      $message->load('user'); // auto-load relation
      $message->append('excerpt'); // use $message->getExcerptAttribube() to make an excerpt
      $message->append('is_read'); // use $message->getIsReadAttribute()

      return $message;
   }
}

This is useful to move a lot of business logic outside the model itself. This also avoids querying extra SQL-records every-time you use $with.

Leave a comment