[英]data not entered to database using Lumen (Laravel)
我是Laravel和Lumen框架的新手。
我正在嘗試使用Lumen框架創建API。我想將數據輸入數據庫。 但是,數據庫使用id,date_created和date_updated更新。 但是我輸入的數據沒有插入那里。 相反,它對於字符串輸入顯示空白,對於整數輸入顯示0。
這是我的控制器代碼:
<?php
namespace App\Http\Controllers;
use App\Place;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PlaceController extends Controller{
public function savePlace(Request $request){
$place = Place::create($request->all());
return response()->json($place);
}
}
這是我的遷移代碼:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePlacesTable extends Migration
{
public function up()
{
Schema::create('places', function (Blueprint $table) {
$table->increments('id');
$table->string('place');
$table->integer('pincode');
$table->integer('bed');
$table->integer('square_feet');
$table->integer('price');
$table->timestamps();
});
}
public function down()
{
Schema::drop('places');
}
}
我做對了嗎? 我應該同時使用其他代碼嗎?
請幫忙。
提前致謝。
編輯:
這是我的地方模型代碼:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Place extends Model{
protected $fillable = ['place', 'pincode', 'bed', 'square_feet', 'price'];
}
編輯2:
我正在從angularjs應用程序(離子框架)發送請求。
這是我的http.post代碼:
app.controller('NavCtrl', ['$scope', '$http', '$location', '$window', function($scope,$http,$location,$window){
$scope.data = {};
$scope.savedata = function(){
$http({
url : "http://localhost/lumen/public/add",
method : "POST",
headers: $headers,
data : {'place':$scope.data.place,'pincode':$scope.data.pincode,'bed':$scope.data.bed,'square_feet':$scope.data.square_feet,'price':$scope.data.price}
})
.success(function(data,status,headers,config){
console.log(data);
$scope.navigat('/success.html');
})
.error(function(){
alert("failed");
})
};
$scope.navigat = function(url){
$window.location.href=url;
};
}]);
這是我的routes.php代碼:
<?php
header("Access-Control-Allow-Origin: *");
$app->get('/', function () use ($app) {
return $app->version();
});
$app->post('lumen/public/add','PlaceController@savePlace');
根據這個答案 ,問題似乎是角度發布數據的方式。 基本上,它試圖將數據作為JSON發布,但是PHP並沒有做任何將JSON數據轉換為請求查詢數據的操作。
要使其正常工作,您需要做兩件事。
首先,您需要將Content-Type
標頭更改為application/x-www-form-urlencoded
。 但是,僅更改內容類型標頭將無法解決問題,因為angular仍將數據作為JSON請求發布。
因此,第二,您需要將以JSON格式發布的數據更改為查詢字符串格式(name = value&name = value)。
因此,將您的代碼更新為以下內容:
$http({
url : "http://localhost/lumen/public/add",
method : "POST",
headers: { "Content-Type" : "application/x-www-form-urlencoded" },
data : [
'place=' + encodeURIComponent($scope.data.place),
'pincode=' + encodeURIComponent($scope.data.pincode),
'bed=' + encodeURIComponent($scope.data.bed),
'square_feet=' + encodeURIComponent($scope.data.square_feet),
'price=' + encodeURIComponent($scope.data.price)
].join('&')
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.