Home » vue » how to access axios response in blade – laravel view

how to access axios response in blade – laravel view

Posted by: admin November 26, 2021 Leave a comment

Questions:

How to access axios result from vue component in blade file? I tried accessing {{value}} within ‘app’ div also. But the error still remains. I want to generate partial views based on the value of axios response.

IssueComponent.vue

<template>
<div>
<div class="form-group">
  <label>Enter Accession No</label>
  <input
    type="text"
    name="accession_no"
    placeholder="Accession No"
    class="form-control"
    v-on:keyup.enter="getData()"
    v-model="query"
  />
</div>
<div>
  <button class="btn btn-info" @click.prevent="getData()">Check</button>
</div>
</template>

<script>
export default {
data() {
return {
  query: "",
  value: []
 };
},
 methods: {
 getData: function() {
  var self = this;
  axios
    .get("/issue-getdata", { params: { q: self.query } })
    .then(function(response) {
      self.value = response.data;
    })
    .catch(function(error) {
      console.log(error);
    })
    .then(function() {
    });
 }
}
};
</script>

create.blade.php

<form action="/issue" method="POST">

<div id="app">
    <issue-component></issue-component>
</div>
{{value}}  ///////// Undefined constant error
<button type="submit" class="button-btn btn-success">Submit</button>
@csrf
</form>

Controller Method

public function getData(Request $request){
    $input = $request->q;
    $acsNo = preg_replace("/[^0-9]/", "", $input);
    $acsNoIssued =  Issue::where('accession_no', '=', $acsNo)->where('is_returned', null)->orwhere('is_returned', 0)->first();
    return response()->json($acsNoIssued);        
}

The Error

Facade\Ignition\Exceptions\ViewException
Use of undefined constant value - assumed 'value' (this will throw an Error in a future version of PHP) (View: D:\ProgrammingSSD\laragon\www\ulclibrary\resources\views\issues\create.blade.php)
Answers:

You can’t. Blade is rendered server side. By the time your vue component makes the request, that {{ $value }} is already parsed and is now a static part of your view.

What you could do is save the state (the information) in VUE, and read it using another VUE component that will display the info (instead of blade).

Guide for states in vue
https://vuex.vuejs.org/guide/state.html

<form action="/issue" method="POST">

<div id="app">
    <issue-component></issue-component>
</div>
<display-component-value></display-component-value>  // Vue component that reads the state you want
<button type="submit" class="button-btn btn-success">Submit</button>
@csrf
</form>