本文实例讲述了laravel框架中控制器的创建和使用方法。分享给大家供大家参考,具体如下:

laravel中我们可以使用 artisan 命令来帮助我们创建控制器文件。

php artisan make:controller testcontroller

testcontroller 控制器名我们可以任意指定。文件默认会创建在 app\http\controllers 目录下。

打开控制器文件,我们就可以添加自已的方法了。

<?php
namespace app\http\controllers;
use illuminate\http\request;
class testcontroller extends controller
{
  public function test()
  {
    echo 'test...';
  }
}

在路由文件 routes/web.php 中配置路由就可以访问了。

route::get('/test', 'testcontroller@test');

如何获取用户的输入,一般推荐通过依赖注入的方式来获取。

<?php
namespace app\http\controllers;
use illuminate\http\request;
class testcontroller extends controller
{
  public function test(request $request)
  {
    //获取所有请求数据
    $data = $request->all();
    //获取指定请求数据
    $id = $request->input('id');
  }
}

laravel中为我们编写 restful 风格的代码,提供了简单方式,只需在创建控制器命令后面加上 –resource 选项。

php artisan make:controller ordercontroller --resource

laravel帮我们创建指定的方法,各自表示不同的意义和作用。

<?php
namespace app\http\controllers;
use illuminate\http\request;
class ordercontroller extends controller
{
  /**
   * display a listing of the resource.
   *
   * @return \illuminate\http\response
   */
  public function index()
  {
    //
  }
  /**
   * show the form for creating a new resource.
   *
   * @return \illuminate\http\response
   */
  public function create()
  {
    //
  }
  /**
   * store a newly created resource in storage.
   *
   * @param \illuminate\http\request $request
   * @return \illuminate\http\response
   */
  public function store(request $request)
  {
    //
  }
  /**
   * display the specified resource.
   *
   * @param int $id
   * @return \illuminate\http\response
   */
  public function show($id)
  {
    //
  }
  /**
   * show the form for editing the specified resource.
   *
   * @param int $id
   * @return \illuminate\http\response
   */
  public function edit($id)
  {
    //
  }
  /**
   * update the specified resource in storage.
   *
   * @param \illuminate\http\request $request
   * @param int $id
   * @return \illuminate\http\response
   */
  public function update(request $request, $id)
  {
    //
  }
  /**
   * remove the specified resource from storage.
   *
   * @param int $id
   * @return \illuminate\http\response
   */
  public function destroy($id)
  {
    //
  }
}

具体方法的作用如下所示:

http 方法 uri 控制器方法 路由名称 作用描述
get /order index order.index 显示所有订单列表
get /order/create create order.create 显示创建订单页面
post /order store order.store 接收提交数据,创建订单
get /order/{id} show order.show 显示单个订单信息
get /order/{id}/edit edit order.edit 显示修改订单页面
put/patch /order/{id} update order.update 接收提交数据,修改订单
delete /order/{id} destroy order.destroy 删除订单

最后我们通过 route::resource() 来绑定上面的所有路由。

route::resource('order', 'ordercontroller');

我们也可以通过命令查看,绑定的路由列表。

php artisan route:list