[英]Create entry with Laravel's Eloquent
你好Stackoverflowers,
我目前正在使用Laravel 4.2開發一個網頁。 我自己已經解決了幾個問題,但是現在我受夠了。 我試圖為我的MySQL-Table structures
創建一個新的數據庫條目。 可以排除連接問題。
所有連接似乎都可以正常工作,因為所有連接均返回200的HTTP狀態-好的,也許您經驗豐富的開發人員可以為我提供幫助! 命名空間還可以,並且所有類都可以訪問。 預先感謝!
問題是:為什么控制器不將任何數據插入數據庫。 我是使用錯誤的Controller-Function create
還是以錯誤的方式使用它?
/app/models/db/Structures.php中的“ Structures
模型”文件
namespace Database;
class Structures extends \Eloquent {
protected $table='structures';
protected $protected = array();
}
/app/controllers/admin/api/StructuresController.php中的相應控制器 (可以排除命名空間Controllers \\ Admin \\ API問題)
public function create($data = null)
{
Structures::create($data)->save();
return Response::json(array('success' => true));
}
我在AngularJS中使用$http
-Service調用上面的Controller
angular.module('PagesService', [])
.factory('Structure', function($http) {
return {
save : function(structureData) {
return $http({
method: 'POST',
url: 'admin/api/structures',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(structureData)
});
}
}
})
這是相應的控制器到服務
angular.module('PagesController', [])
.controller('StructureController', function($scope, $http, Structure) {
$scope.newStructure = function() {
Structure.save({
'title': "Änderbar",
'type': "markdown",
'page-id': 1,
'order': 3,
'class': '',
'text': "Testtext"
})
.success(function(data) {
...
})
.error(function(data) {
console.log(data);
});
return false;
}
});
routes.php
文件(摘錄)
Route::resource('admin/api/structures', 'Controllers\Admin\API\StructuresController');
現在,我發現了導致一個大問題的幾個問題。 如假定的那樣,正確配置了名稱空間,數據庫遷移和$http
-Services。 非常感謝@lukasgeiter。
我發現的第一個問題是AngularJS中的$http
-Service調用,例如:
$http({
method: 'POST',
url: 'admin/api/structures',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(structureData)
})
...在我的StructureController
調用函數store() (請參見上面的route.php摘錄)
我發現的第二個問題是我的模型白名單 。 我用所有要修改的列填充了$fillable
-array()。
protected $fillable = ['title', 'page-id', 'type', 'order', 'class', 'src', 'figcaption', 'text', 'data'];
我發現的最后一個問題是,可以用我的PagesController
(AngularJS)中的Structure.get()
作為參數給數據填充create
function。
Structures::create(
array(
'title' => Input::get('title'),
'page-id' => Input::get('page-id'),
'type' => Input::get('type'),
'order' => Input::get('order')
)
);
請確保在控制器頂部包括Illuminate\\Support\\Facades\\Input
類,例如:
namespace ...;
use ..., Illuminate\Support\Facades\Input;
class StructuresController extends \BaseController {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.