[Vuejs]-How to get data from DB using axios

0👍

in your vue.

export default {
  data(){
   return{
    id: this.$route.params.id,
    projet:{}
  }
},
methods:{
 //GETID
 afficherProjet(){
   axios.get('api/getProject/'+this.id)
      .then(data => {
              this.projet = data.data;
           });
 }
},
mounted() {
  console.log('Component mounted.')
  this.afficherProjet();
}

File in routes api.php

//ALL
Route::get('getProjects', ['uses' =>'API\ProjetController@getProjects']);
//SPECIFIQ ID
Route::get('getProject/{id}', ['uses' =>'API\ProjetController@getProject']);

In your controller, app/Http/API/ProjetController

public function getProjects()
{
   return Projet::latest()->paginate(15);
}

public function getProject($id)
{
  return Projet::findOrFail($id);
}

Your model projet

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Projet extends Model
{
   public $timestamps = false;

   protected $table = 'projets';

   protected $fillable = [
     'name',
     'durre',
     'description',
     'budget',
     'owner'
   ];
}

Do you have your model?

Your error comes from the ‘data.data’ i thing it’s empty, you should just call ‘data’.

Personally i prefer Mounted.

I thing now it’s working!

Leave a comment