laravel:创建一个controller(10.27.0)
一,从命令行创建controller
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan make:controller NewsController
INFO Controller [app/Http/Controllers/NewsController.php] created successfully.
liuhongdi@lhdpc:/data/laravel/dignews$ ls app/Http/Controllers/NewsController.php
app/Http/Controllers/NewsController.php
二,php代码
1,App\Http\Controllers\NewsController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class NewsController extends Controller { //直接返回字符串 public function home(){ return 'Hello, World!' ; } //返回json格式数据 public function homejson(){ //直接返回数组,相当于return json_encode(['msg'=>'Hello, World!']); return [ 'msg' => 'Hello, World!' ]; } } |
2,在路由中添加:
routes/web.php中添加
1
2
3
4
5
6
|
use App\Http\Controllers\NewsController; Route::controller(NewsController:: class )->group( function () { Route::get( '/news/home' , 'home' ); Route::get( '/news/homejson' , 'homejson' ); }); |
说明:
如果在api.php中添加路由,则访问时形如:
http://192.168.219.6:8004/api/news/homejson
三,测试效果
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/16/laravel-chuang-jian-yi-ge-controller/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
四,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0