从迁移命令开始
php artisan make:migration CreateProductsTable
在这里定义你的结构,它看起来像这样:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('sku')->unique();
$table->double('price');
$table->timestamps();
});
在这之后你需要创建一个模型:
php artisan make:model Product
这会在您的“App”文件夹中创建一个 Product.php 文件
class Product
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'sku', 'price'
];
}
如果 $fillable 中未定义字段,您将无法发布该字段。
现在创建一个 ProductController
php artisan make:controller ProductController
这必须看起来像这样:
class ProductController extends Controller
{
public function __construct()
{
//$this->middleware('auth');
}
public function index(Request $request) {
$data = $request->all();
$product= Product::create([
'name' => $data['product_name'],
'sku' => $data['product_sku'],
'price' => $data['product_price'],
]);
}
}
当然可以在products表中添加user_id等字段,设置不同表之间的关系。