【Laravel 7.x / Vue 4.x】LaravelでVue Selectを使ってaxios.postで送信する。
内容はタイトルの通りで、方法としては2つあります。
①Vue jsのdataの中にoptionを作って選択肢をあらかじめ決めておいてプルダウンメニューに表示する方法
②選択肢が増えたりするのでデータベースから選択肢を持ってくるやり方
LaravelでVue.jsのインストールやv-selectのインストール方法は他の方がたくさんしているので、そこの説明は省きます。
まずは①から解説していきます。
①Vue jsのdataの中にoptionを作って選択肢をあらかじめ決めておいてプルダウンメニューに表示する方法
テーブル名:Reports
カラム名:job_type
とする。
create.blade.php
<div id="app">
<form @submit.prevent="addNewReport">
<v-select :options="options" v-model="job_type" class="w-full text-lg bg-white" />
<input class="w-full bg-indigo-700 font-semibold text-white py-2 px-4 rounded" type="submit" value="送信する" :disabled="ObserverProps.invalid || !ObserverProps.validated">
</form>
</div>
Vue.jsの記述
<script>
// Vue Selectの読み込み
Vue.component('v-select', VueSelect.VueSelect);
var app = new Vue({
el: '#app',
data() {
return {
job_type: '',
options: ['メンテナンス', '保守', '運用'],
}
},
methods: {
addNewReport() {
axios.post('/report/store', {
job_type: this.job_type
})
.then(response => {
alert('作業報告を登録しました')
window.location.href = '/report'; // リダイレクト先のURL
})
.catch(error => {
console.log('false')
});
}
}
});
</script>
これで完了。あとはコントローラーのstoreメソッドでsaveすれば無事にpost出来ると思います!!
続いて、
②選択肢が増えたりするのでデータベースから選択肢を持ってくるやり方
テーブル名:Reports
カラム名:customer(顧客)
とする。
create.blade.php
<div id="app">
<form @submit.prevent="addNewReport">
<v-select :options="customer_options" label="name" v-model="customer_id" :reduce="customer => customer.id" class="w-full text-lg bg-white" placeholder="客先" />
<input class="w-full bg-indigo-700 font-semibold text-white py-2 px-4 rounded" type="submit" value="送信する" :disabled="ObserverProps.invalid || !ObserverProps.validated">
</form>
</div>
label="name"
セレクトボックスに表示させるのは顧客名。
:reduce="customer => customer.id"
データに送信するのは顧客のID。
Vue.jsの記述
<script>
// Vue Selectの読み込み
Vue.component('v-select', VueSelect.VueSelect);
var app = new Vue({
el: '#app',
data() {
return {
customer_id: '',
customer_options: <?php echo $customers; ?>
}
},
methods: {
addNewReport() {
axios.post('/report/store', {
customer_id: this.customer_id
})
.then(response => {
alert('登録に成功しました!')
window.location.href = '/report';
})
.catch(error => {
console.log('false')
});
}
}
});
</script>
となります!
あとはControllerに保存の記述を書いて終了。
ReportController.php
public function store(Request $request)
{
$report = new Report;
$report->customer_id = $request->input('customer_id');
$report->save();
}
ほとんどの処理をVueで書いてあるので、コントローラーはめっちゃシンプルになります。
以上!!
参考にさせていただいた記事
https://www.kabanoki.net/3786/
https://note.com/kawa1228/n/n0f53a7670d1b
ありがとうございました🙇♂️
この記事が気に入ったらサポートをしてみませんか?