Dustin
Dustin

Reputation: 112

return data object to vue component using laravel 5.6 and axios

I am trying to build an availability carousel. It will show the days of the week, and what time someone is available. I am using Laravel and vue.js. I have done the web api, and I can get the data object following the route

Route::group(['prefix' => '/{area}'], function () {
    Route::get('/{tutor}/availability','Tutor\AvailabilityController@show'); 
});

with this in my availability controller

public function show(Request $request, Area $area, Tutor $tutor)
{
    $availability = $tutor->availability()->get();

    return response()->json([
        'data' => $availability
    ], 200);
}

That all works.

But when I try and pull it into Vue, nothing shows up. I can't seem to figure out what I might be missing.

I pulled the vue component into blade using the following, and passing in the area and tutor id

<availability area-id="{{ $area->slug }}" tutor-id="{{ $tutor->slug }}">
</availability>

and in Availability.vue, I think where I am going wrong is pulling the data in with props, but I am really not sure anymore.

<script>


  $(document).ready(function() {

      $("#availability").owlCarousel();

  });

  export default {

    props: {
      areaId: null,
      tutorId: null
    },
    data () {
      return {
        availability: []
      }
    },

    methods: {
      getAvailability () {

        axios.get( '/' + this.areaId + '/' + this.tutorId + '/availability').then((response) => {
          console.log(response.json());
        });
      }
    },
    ready () {
      this.getAvailability();
    }
  }


</script>

Thank you for the help.

Upvotes: 0

Views: 4844

Answers (1)

Badu
Badu

Reputation: 1082

Axios response object has data field which contains the response from the server. To get the data use

response.data

Also for Vue 2.0 components use mounted instead of ready for when the component is ready. If you are only loading data from the server (and not manipulating the DOM) you can use created instead.

export default {

    props: {
      areaId: null,
      tutorId: null
    },
    data () {
      return {
        availability: []
      }
    },

    methods: {
      getAvailability () {
        var that = this;
        axios.get( '/' + this.areaId + '/' + this.tutorId + '/availability')
        .then((response) => {
          console.log(response.data); // should print {data: availability_object}

          // Set this component's availability to response's availability               
          that.availability = response.data.data;

          //OR
          //Add response's availability to the components' availability
          that.availability.push(response.data.data);
        });
      }
    },
    mounted () {
      this.getAvailability();
    }
 }
</script>

Upvotes: 2

Related Questions