当前位置:Gxlcms > PHP教程 > [Laravel]Laravel的根本使用

[Laravel]Laravel的根本使用

时间:2021-07-01 10:21:17 帮助过:15人阅读

[Laravel] Laravel的基本使用

[Laravel] Laravel的基本HTTP路由

使用Laravel的基本路由,实现get请求响应,找到文件app/Http/routes.php

调用Route的静态方法get(),实现get响应,参数:string类型的路径,匿名函数function(){}

匿名函数内部,返回string数据

实现post,put,delete的请求,同上

实现get传递参数的路由,调用Route的静态方法get(),参数:路径,匿名函数

路径,大括号包裹参数名,不含$,例如:’/user/{id}’

匿名函数,接收参数,例如:function($id){}

[Laravel] Laraval的基本控制器

在app/Http/Controllers目录下,新建一个Index/IndexController.php

定义命名空间,namespace App\Http\Controllers\Index

引入Controller基本控制器,use App\Http\Controllers\Controller

定义IndexController继承Controller

实现方法index,返回数据

定义路由指定控制器的行为,例如:Route::get("/index","Index\[email protected]");,

注意命名空间部分,新建的控制器是在根命名空间下面,指定的时候添加自己新加的命名空间

[Laravel] Laravel的基本视图

在目录resources/views/下面,创建index/index.php

在控制器中使用函数view()来调用模板,参数:文件路径(.分隔目录),数据

路由:routes.php

php/*|--------------------------------------------------------------------------| Routes File|--------------------------------------------------------------------------|| Here is where you will register all of the routes in an application.| It's a breeze. Simply tell Laravel the URIs it should respond to| and give it the controller to call when that URI is requested.|*//*测试get post*/ Route::get('/', function () {    $url=url("index");    return "Hello World".$url;    //return view('welcome');});Route::post("/post",function(){    return "测试post";});/*传递参数*/Route::get("/user/{id}",function($id){    return "用户".$id;});/*使用控制器*/Route::get("/index","Index\[email protected]");/*|--------------------------------------------------------------------------| Application Routes|--------------------------------------------------------------------------|| This route group applies the "web" middleware group to every route| it contains. The "web" middleware group is defined in your HTTP| kernel and includes session state, CSRF protection, and more.|*/Route::group(['middleware' => ['web']], function () {    //});

控制器:IndexController.php

phpnamespace App\Http\Controllers\Index;use App\Http\Controllers\Controller;class IndexController extends Controller{    public function index(){        $data=array();        $data['title']="Index控制器";        return view("index.index",$data);    }}

模板:index.php

    <body>        <div class="container">            <div class="content">                <div class="title">php echo $title;?>div>            div>        div>    body>

人气教程排行