Ad

How To Get Data From DB Using Axios

- 1 answer

I’m having a problem.

i have list of project i want when i click in one project he take me to another page(components) this is the component ProjectDetail when i can find the detail of that project Inside of it, I have this block of code: this is the route who take me to another components:

 {path: '/detail/:id', name: detail , component: detail },

I want to get the project with the id in the url detail from DB w but nothing Happen this is ProjectDetail.vue:

export default {
      data(){
      return{
      id: this.$route.params.id,
    projets:[],
   projet:{
    id:'',
   name:'',
     durre:'',
  description:'',
      budget:'',
  owner:'',
      }
   }
 },
      methods:{ 
    afficherProjets(){
       axios.get('api/getProjects/'+this.id)
         .then(data => {
           this.projets = data.data;
               });
                  }
           },
          mounted() {
           console.log('Component mounted.')
           this.afficherProjets();
        }
           }

and this is my controller:

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

Answer

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\[email protected]']);
//SPECIFIQ ID
Route::get('getProject/{id}', ['uses' =>'API\[email protected]']);

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!

Ad
source: stackoverflow.com
Ad