批改状态:合格
老师批语:完全的不错 , 图文直观
1、通过artisan和手动创建控制器,并通过设置路由访问


<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Home extends Controller
{
public function index(){
echo '我是控制器,路由实现方法';
}
}
?>点击 "运行实例" 按钮查看在线实例
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', function () {
return ('home');
});
Route::get('/home','home@index');
?>点击 "运行实例" 按钮查看在线实例
2、通过artisan和手动创建模型,并通过配置数据库实现从表中获取数据
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'user';
protected $primaryKey = 'uid';
// 获取表中所有记录
public function abc(){
return $this->get()->toarray();
}
}
?>点击 "运行实例" 按钮查看在线实例
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class Home extends Controller
{
public function index(User $user){
echo '<pre>';
$res = $user->abc();
foreach($res as $k => $val){
$res[$k] = (array)$val;
}
print_r($res);
}
}
?>点击 "运行实例" 按钮查看在线实例

通过artisan创建模型

3、在控制器中引用模型,通过模型方法获取数据库中的数据,并输出
<?php
namespace App\Http\Controllers;
use App\Models\Users;
use Illuminate\Http\Request;
class Home extends Controller
{
public function index(Users $users){
echo '<pre>';
$res = $users->cc();
foreach($res as $k => $val){
$res[$k] = (array)$val;
}
$users = Users::find(1);
print_r($users->name);
}
}
?>点击 "运行实例" 按钮查看在线实例

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号