0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelから受け取ったデータをVueで非同期で更新する。

Posted at

はじめに

LaravelからVueにデータを渡すときのメモを大まかに書いておきます。

環境
Laravel 8.33.1
vue: 2.5.17


api.phpに書くのが正しいのかweb.phpに書くのがいいのかわからないのですが、どちらでも動く、違いといえばapi/をつけるかどうかくらいにしか理解できていないです。。

web.php

 Route::get('/', [ProductController::class,'index']);
 Route::get('/Products', [ProductController::class,'getProducts']);

テーブル

  $table->id();
  $table->string('name');
  $table->string('description');
  $table->timestamps();

Resourceをつくって必要なデータだけを取り出します。
php artisan make:resource ProductResource

Resourceを書き換え。timestampsは必要ないので取り除いてる。
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->word,
            'description' => $this->description,
        ];
        //デフォルト↓
        // return parent::toArray($request);
    }

ProductController

    
   //useを追加
   use App\Models\Product;
   use App\Http\Resources\ProductResource;
    
    //viewを返す
    public function index()
    {
        return view('index');
    }
    
    //Vueにデータを渡す
    public function getProducts()
    {
    return ProductResource::collection(Product::all());

    }


View。appで囲む。script を忘れずに書く
     <div id="app">
        <product-page/>
    </div>

    <script src="{{ asset('js/app.js') }}"></script>


Laravelからのデータをaxiosで受け取る。受け取ったデータを空の配列のproductsに入れる。for文で回す
 <template>
  <div >
      <p v-for="product in products" :key='product.id'>
      {{ product.name}}
    {{ product.description}}
       </p>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      products: [],
    };
  },
  mounted() {
    this.loadEnglishWord();
  },
  methods: {
//Laravelからのデータをaxiosで受け取る
    loadProducts: function () {
      axios
        .get("/products")
        .then((response) => {
          //  console.log( response)
          this.products= response.data.data;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
};
</script>

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?