am trying to retrieve data from a database using vuejs ajax call with a plugin called vue-resource . Unfortunately, the json data object contains the html page and not the actual data from the database. Can someone please tell me what am doing wrong? This is my code:
routes.php
<?php
Route::get('find', 'FruitsCtrl@index');
fruitsctrl.php (controller)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Fruit;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class FruitsCtrl extends Controller
{
public function index(Request $req){
$fruits = Fruit::all();
return view('fruitsHome', $fruits);
}
}
fruit.php (model)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Fruit extends Model
{
protected $fillable = [
'id', 'name', 'type'
];
}
fruitshome.blade.php (view)
<head>
<meta id="token" content="{{ csrf_token() }}">
</head>
<body>
<div class="row" id="vapp">
<ul>
<li v-for="fruit in fruits">
@{{ fruit.name }}
@{{ fruit.type }}
</li>
</ul>
</div>
<body>
app.js (javascript)
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
var v = new Vue({
el : "#vapp",
ready :function () {
this.fetchFruits();
},
data : {
fruit : {id:'', name:'', type:''},
fruits : []
},
methods : {
fetchFruits : function(){
this.$http.get('/find').then(function(res){
this.fruits = res;
},function (data){
console.log(error ...);
});
}
}
});
You're currently returning a view from your controller:
class FruitsCtrl extends Controller
{
public function index(Request $req){
$fruits = Fruit::all();
return view('fruitsHome', $fruits);
}
}
Instead, you can return the Eloquent results directly and they'll be output as JSON:
class FruitsCtrl extends Controller
{
public function index(Request $req){
$fruits = Fruit::all();
return $fruits;
}
}
I think you need to set table name in the model like this :
class Fruit extends Model
{
protected $table = 'fruits';
protected $fillable = [
'id', 'name', 'type'
];
}
You also need to update index method like this :
public function index(Request $req){
$fruits = Fruit::all();
return view('fruitsHome')->withFruits($fruits);
}
and finally update the blade :
<li v-for="fruits in fruit">
@{!! $fruits->name !!}
@{!! $fruits->type !!}
</li>
Let me know if it helps you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.