Home > Enterprise >  Blank Data by Fetching data from DB using Laravel 9 and Vue.js 3 and Axios
Blank Data by Fetching data from DB using Laravel 9 and Vue.js 3 and Axios

Time:12-01

Hello i using Laravel 9 and Vue.js 3, with Axio and i am trying to fecht some data from my data base, to appear inside a select list options, however i am not getting anything (neither any error, just blank data...)

I created my model Produto

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Produto extends Model
{
    use HasFactory;
    protected $table = "produto";
    protected $guarded = []; 
}

created the correct migration

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('produto', function (Blueprint $table) {
            $table->id();
            $table->string("nome");
            $table->double("preco");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('produto');
    }
};

Created my controller ProdutoController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Produto;

class ProdutoController extends Controller
{
   /** 
     *Retorna os dados dos Produtos
     *
     * @return void
     */
    public function getProdutos()
    {
        $data = Produto::get();
        return response()->json($data);
    }
}

Defined my route

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProdutoController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});


 
Route::get('get_produtos', [ProdutoController::class, 'getProdutos']);
//Route::post('produtos', [ProdutoController::class, 'setProdutos']);


For testing i tried localhost:8000/get_produtos and it appeared my data as expected, so i think this part is correct

[{"id":1,"nome":"Telemovel","preco":124.55,"created_at":null,"updated_at":null},{"id":2,"nome":"Tablet","preco":600.99,"created_at":null,"updated_at":null},{"id":3,"nome":"Portatil","preco":501,"created_at":null,"updated_at":null},{"id":4,"nome":"Caneta","preco":2.55,"created_at":null,"updated_at":null}]

In my template i used this Select

<div :id="selectProdutoID" >
            <div :id="optionId"  >
                            <select  :id="selectId"  class=' form-select form-control-md' v-model='prod' @change="onchange($event)">
                                <option v-for='data in produto' :value='data.id'>{{ data.nome }} </option>
                            </select>
                        </div>

And finally here is my script

<script>


export default{
name:"app",
components: {

},


data() {
  return{
    blankID:"blank",
    tituloID:"titulo",
    ClienteID:"nomeCliente",
    selectId:"selectID",
    dropID:"drop",
    adicionarID:"adicionarId",
    selectProdutoID:"selectProduto",
    optionId:"optionId",
    qtdID:"qtdId",
    boxId:"boxId",
    produto: [],

    onchange(e){
        console.log(e.target.value);
    }
}
},

methods:{
            getProdutos: function(){
                axios.get('get_produtos')
                    .then(function (response) {
                        this.produtos = response.data;
                    }.bind(this));
            }
        },
        created: function(){
            this.getProdutos()
        }
    }


   
</script>

It doesn't even get me an error, just a select with empty content , and i tried to check other solutions i found here, but nothing worked for now. I believe the error is happening somewhere in the the template/script part, but i´ve been trying everything i found and still with no luck

Thank you in advance

EDIT:

Found out this tutorial https://www.tutsmake.com/laravel-9-vue-js-axios-get-request-tutorial/

and then changed my script methods to

methods: {
            getProdutos(){
                axios.get('/get_produtos')
                     .then((response)=>{
                       this.produtos = response.data.produtos
                     })
            }
        },
        created() {
            this.getProdutos()
        }

However data continues to not appear on my select

CodePudding user response:

Found a solution to my problem. For some reason if i use «this» directly Axios doesn't work, so i had to create a variable, and it worked

methods: {
            getProdutos(){
                var vm = this
                axios.get('/get_produtos')
                     .then((response)=>{
                       vm.produtos = response.data
                     })
            }
        },
        created() {
            this.getProdutos()
        }

  • Related