shigg
shigg

Reputation: 802

How do I pass a route parameter to Vue.js from Laravel

I have a route like this to fetch a post with the associated comment.

Route::get('/api/topics/{category_id}/{title}', function($category_id, $title){
    return App\Topic::with('comments')->where(compact('category_id','title'))->firstOrFail();
});

The thing is how can I pass a parameter variables to Vue.js?In this case "category_id" and "title",so Vue can fetch the post as well as the comments.

Below is my Vue instance which gives me this error:

main.js:11749Uncaught ReferenceError: category_id is not defined

Vue instance

new Vue({


el: '#comment',

methods: {

    fetchComment: function (category_id, title) {
        this.$http.get('/api/topics/' + category_id + '/' + title ,function (data) {
            this.$set('topics',data)
        })
    }


},
ready: function () {
    this.fetchComment(category_id, title)
}
}); 

method to show a certain post

public function show($category_id, $title)
{

$topic = Topic::where(compact('category_id','title'))->firstOrFail();

$comments = Comment::where('topic_id',$topic->id)->get();

return view('forums.category', compact('topic','comments'));
}

Upvotes: 3

Views: 4105

Answers (1)

Ata
Ata

Reputation: 312

ForumsController.php

public function show($category_id, $title) {
    $topic = Topic::where('category_id', $category_id)
        ->where('title', $title)
        ->firstOrFail();

    return view('forums.category')
        ->with('topic', $topic);
}

Javascript

var category_id = '{{ $topic->cataegory_id }}';
var title       = '{{ $topic->title }}';

new Vue({
  el: '#comment',

  methods: {
    fetchComment: function(category_id, title) {
      this.$http.get('/api/topics/' + category_id + '/' + title, function(data) {
        this.$set('topics', data);
      })
    }


  },

  ready: function() {
    this.fetchComment(category_id, title);
  }
});

Upvotes: 2

Related Questions