这是我在CategoryController.php
中的代码
public function addCategory(Request $request){
if($request->isMethod('post')){
$data = $request->all();
// echo "<pre>", print_r($data);die;
$category = new Category;//in the http
$category->name = $data['category_name'];
$category->description = $data['description'];
$category->url = $data['url'];
$category->save();
}
else{
}
return view('admin.categories.add_category');
}
}
我在数据库中的表名是categories
答案 0 :(得分:2)
第1步:数据库连接。
https://laravel.com/docs/5.7/database
Laravel在幕后自动设置连接。您的config / database.php文件包含数据库凭据和主机(此处的实际值通常存储在应用程序根目录中的.env文件中)。 Laravel将启动,获取那些database.php配置值并连接到数据库
第2步:雄辩的ORM
https://laravel.com/docs/5.7/eloquent
Laravel结合了Eloquent ORM,用于抽象化与数据库的通信。数据库中的每个表都可以绑定到一个类,该类被雄辩地称为Model。这就是Category.php类文件的外观:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
// This variable tells eloquent which table this model is trying to access.
protected $table = 'categories';
}
然后在CategoryController中创建一个新模型。
// Create a new model instance - this is like creating a new row in an SQL editor.
$category = new Category;
// Here, you set the field values of the row.
// Each of the attributes below corresponds to a column name in the table.
// Right now this data is not in the database.
$category->name = $data['category_name'];
$category->description = $data['description'];
$category->url = $data['url'];
// And here we call the save() method, to actually execute the insert command.
// This is going to construct a query behind the scenes, and using the database
// connection set in configuration file, send it to the server and execute it.
$category->save();
// And here, a new row is already inserted in the database and you can access
// all of it's values.
var_dump($category->id);
我建议您阅读Laravel文档-的确写得很好并且易于理解,可以在Google中搜索很多这些基础知识,并且那里有很多信息。