一、前台首页数据
1.1 创建控制器
运行命令php artisan make:controller Web/IndexController 写入首页获取数据方法:
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\BaseController;
use App\Models\Good;
use App\Models\Slide;
class IndexController extends BaseController
{
function index() {
$slides = Slide::where('status', 1)
->orderBy('seq')
->get();
$categories = cache_category();
$goods = Good::where('is_on', 1)
->where('is_recommend', 1)
->get();
return $this->response->array([
'slides' => $slides,
'categories' => $categories,
'goods' => $goods,
]);
}
}
1.2 前台路由
routes/api.php 这里写我们的前台路由:
<?php
use App\Http\Controllers\Web\IndexController;
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->get('/index', [IndexController::class, 'index']);
$api->group(['middleware' => ['api.auth', 'check.permission']], function ($api) {
});
});
1.3 创建分类填充
运行命令php artisan make:seed CategorySeeder 创建分类的填充文件:
对分类进行数据添加:
<?php
namespace Database\Seeders;
use App\Models\Category;
use Illuminate\Database\Seeder;
class CategorySeeder extends Seeder
{
public function run()
{
$categories = [
[
'name' => '电子产品',
'group' => 'goods',
'pid' => 0,
'level' => 1,
'children' => [
[
'name' => '手机',
'group' => 'goods',
'level' => 2,
'children' => [
[
'name' => '华为',
'group' => 'goods',
'level' => 3,
],
[
'name' => 'oppo',
'group' => 'goods',
'level' => 3,
],
]
],
[
'name' => '相机',
'group' => 'goods',
'level' => 2,
'children' => [
[
'name' => '索尼',
'group' => 'goods',
'level' => 3,
],
[
'name' => '佳能',
'group' => 'goods',
'level' => 3,
],
]
]
]
],
[
'name' => '车',
'group' => 'goods',
'pid' => 0,
'level' => 1,
'children' => [
[
'name' => '轿车',
'group' => 'goods',
'level' => 2,
'children' => [
[
'name' => '红旗',
'group' => 'goods',
'level' => 3,
],
[
'name' => '吉利',
'group' => 'goods',
'level' => 3,
],
]
],
[
'name' => '自行车',
'group' => 'goods',
'level' => 2,
'children' => [
[
'name' => '小黄车',
'group' => 'goods',
'level' => 3,
],
[
'name' => '小蓝车',
'group' => 'goods',
'level' => 3,
],
]
]
]
]
];
foreach($categories as $one) {
$l1 = $one;
unset($l1['children']);
$l1_model = Category::create($l1);
foreach($one['children'] as $two) {
$l2 = $two;
unset($l2['children']);
$l2['pid'] = $l1_model->id;
$l2_model = Category::create($l2);
$l2_model->children()->createMany($two['children']);
}
}
forget_cache_category_all();
}
}
执行填充命令:php artisan db:seed --class=CategorySeeder 效果:
在学习的php的路上,如果你觉得本文对你有所帮助的话,那就请关注点赞评论三连吧,谢谢,你的肯定是我写博的另一个支持。
|