• Laravel 使用简述


    开始使用laravel

    在此之前我们需要修改一些配置:

    • app/config/app.php 文件中的 debug 选项设置为 true (注:开启开发模式,更友好的开发提示;网站运行时则关闭);
    • app/config/database.php 文件中的 default 选项设置为你设定的数据库;

      在博客程序中,我们要创建一个新“资源”。资源是指一系列类似的对象,比如文章,人和动物。

      资源可以被创建、读取、更新和删除,这些操作简称 CRUD。

      Laravel 提供了资源控制器可以简单的建立跟资源相关的 RESTful 控制器。 创建文章资源后,app/routes.php 文件的内容新增如下:

      Route::resource('articles', 'ArticlesController');

    执行 $ php artisan routes 任务,会看到定义了所有标准的 REST 动作。输出结果中各列的意义稍后会说明。

    +--------+-----------------------------------+------------------+----------------------------+----------------+---------------+
    | Domain | URI                               | Name             | Action                     | Before Filters | After Filters |
    +--------+-----------------------------------+------------------+----------------------------+----------------+---------------+
    |        | GET|HEAD /                        |                  | WelcomeController@index    |                |               |
    |        | GET|HEAD articles                 | articles.index   | ArticlesController@index   |                |               |
    |        | GET|HEAD articles/create          | articles.create  | ArticlesController@create  |                |               |
    |        | POST articles                     | articles.store   | ArticlesController@store   |                |               |
    |        | GET|HEAD articles/{articles}      | articles.show    | ArticlesController@show    |                |               |
    |        | GET|HEAD articles/{articles}/edit | articles.edit    | ArticlesController@edit    |                |               |
    |        | PUT articles/{articles}           | articles.update  | ArticlesController@update  |                |               |
    |        | PATCH articles/{articles}         |                  | ArticlesController@update  |                |               |
    |        | DELETE articles/{articles}        | articles.destroy | ArticlesController@destroy |                |               |
    +--------+-----------------------------------+------------------+----------------------------+----------------+---------------+
    
    

    下一节,我们会加入新建文章和查看文章的功能。这两个操作分别对应于 CRUD 的 C 和 R,即创建和读取。

    5.1 挖地基

      首先,程序中要有个页面用来新建文章。一个比较好的选择是 /articles/create。这个路由前面已经定义了,可以访问。

      打开 http://localhost:8000/articles/create ,会看到如下的路由错误:

      产生这个错误的原因是,没有定义用来处理该请求的控制器。解决这个问题的方法很简单:创建名为 ArticlesController 的控制器。执行下面的命令即可:

      $ php artisan controller:make ArticlesController

      打开刚生成的 app/controllers/ArticlesController.php 文件,控制器就是一个类,继承自 BaseController。在这个 ArticlesController 类中定义了对应的资源动作。

    动作的作用是处理文章的 CRUD 操作。

      修改 ArticlesController.php 文件中的

        public function create()
        {
            //
        }
    

      为

        public function create()
        {
            return View::make('articles.create');
        }
    

    在 PHP 中,方法分为 public、private 和 protected 三种,只有 public 方法才能作为控制器的动作。

      现在刷新 http://localhost:8000/articles/create ,会看到一个新错误:

      产生这个错误的原因是,Laravel 希望这样的常规动作有对应的视图,用来显示内容。没有视图可用,Laravel 就报错了。

      新建文件 app/views/articles/create.blade.php,写入如下代码:

      <h1>New Article</h1>

      再次刷新 http://localhost:8000/articles/create , 可以看到页面中显示了一个标头。现在路由、控制器、动作和视图都能正常运行了。

    5.2 首个表单

      要在模板中编写表单,可以使用“表单构造器”。Laravel 中常用的表单构造器是 Form。在 app/views/articles/create.blade.php 文件中加入以下代码:

    {{ Form::open() }}
        <p>
            {{ Form::text('title') }}
        </p>
        <p>
            {{ Form::text('text') }}
        </p>
        <p>
            {{ Form::submit('submit') }}
        </p>
    {{ Form::close() }}
    

      现在刷新页面,会看到上述代码生成的表单。在 Laravel 中编写表单就是这么简单!

      在 Form 方法的块中,Form::text 创建了两个标签和两个文本字段,一个用于文章标题,一个用于文章内容。最后,Form::submit 创建一个提交按钮。

      不过这个表单还有个问题。如果查看这个页面的源码,会发现表单 action 属性的值是 /articles/create。这就是问题所在,因为其指向的地址就是现在这个页面,

    而这个页面是用来显示新建文章表单的。要想转到其他地址,就要使用其他的地址。这个问题可使用 Form::open 方法的 url 参数解决。在 Laravel 中,

    用来处理新建资源表单提交数据的动作是 store,所以表单应该转向这个动作。

      修改 app/views/articles/create.blade.php 文件中的 Form::open,改成这样:

      {{ Form::open(array('url' => 'articles')) }}

      这里,我们把 url 参数的值设为 articles 。对应的地址是 /articels,默认情况下,这个表单会向这个路由发起 POST 请求。这个路由对应于 ArticlesController 控制器的 store 动作。

      表单写好了,路由也定义了,现在可以填写表单,然后点击提交按钮新建文章了。

    5.3 创建文章

      提交表单,会看到一个白屏。现在暂且不管这个错误。store 动作的作用是把新文章保存到数据库中。

      提交表单后,其中的字段以参数的形式传递给 Laravel。这些参数可以在控制器的动作中使用,完成指定的操作。要想查看这些参数的内容,可以把 store 动作改成:

      public function store()
      {
          dd(Input::all());
      }
    

      dd 函数为 Laravel 内置的打印输出函数,Input::all() 取得所有发出请求时传入的输入数据。

      如果现在再次提交表单,不会再看到白屏错误,而是会看到类似下面的文字:

      array (size=3)
        '_token' => string 'plx6TrGRWfHakBlKybUzkRTH8r712JU4rWfiPTs7' (length=40)
        'title' => string 'First article!' (length=14)
        'text' => string 'This is my first article.' (length=25)
    

      store 动作把表单提交的参数显示出来了。不过这么做没什么用,看到了参数又怎样,什么都没发生。

    5.4 创建 Article 模型

      在 Laravel 中,模型的名字使用单数,对应的数据表名使用复数

      创建 app/models/Article.php 并写入以下代码:

      <?php
    
        class Article extends Eloquent {
    
        }
    

      注意我们并没有告诉 Eloquent Article 模型会使用哪个数据库表。若没有特别指定,系统会默认自动对应名称为「类名称的小写复数形态」的数据库表。所以,在上面的例子中, Eloquent 会假设 Article 将把数据存在 articles 数据库表。

    5.5 运行迁移

      使用 Artisan CLI 的 migrate:make 命令建立迁移文件:

      $ php artisan migrate:make create_articles_table --create=articles

      迁移文件会建立在 app/database/migrations 目录下,文件名会包含时间戳,用于在执行迁移时用来决定顺序。

      app/database/migrations/2014_09_03_084339_create_articles_table.php (你的迁移文件名可能有点不一样)文件的内容如下所示:

      <?php
    
        use IlluminateDatabaseSchemaBlueprint;
        use IlluminateDatabaseMigrationsMigration;
    
      class CreateArticlesTable extends Migration {
    
        /**
         * Run the migrations.
         *
         * @return void
         */
          public function up()
          {
              Schema::create('articles', function(Blueprint $table)
              {
                  $table->increments('id');
                  $table->timestamps();
              });
          }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
          public function down()
          {
              Schema::drop('articles');
          }
      }
    

    修改其中的创建代码为:

            Schema::create('articles', function(Blueprint $table)
            {
                $table->increments('id');
                $table->string('title');
                $table->text('text');
                $table->timestamps();
            });
    

      在这个迁移中定义了一个名为 up 的方法,在运行迁移时执行。up 方法中定义的操作都是可以通过 down 方法实现可逆的,Laravel 知道如何撤销这次迁移操作。

    运行迁移后,会创建 articles 表,以及一个字符串字段和文本字段。同时还会创建两个时间戳字段,用来跟踪记录的创建时间和更新时间。

      然后,使用 Artisan 命令运行迁移:

      $ php artisan migrate

      Laravel 会执行迁移操作,告诉你创建了 articles 表。

    Migration table created successfully. Migrated: 2014_09_03_084339_create_articles_table

    5.6 在控制器中保存数据

      再回到 ArticlesController 控制器,我们要修改 store 动作,使用 Article 模型把数据保存到数据库中。

      打开 app/controllers/ArticlesController.php 文件,把 store 动作修改成这样:

        public function store()
        {
          $article = Article::create(array('title'=>Input::get('title'), 'text'=>Input::get('text')));
          return Redirect::route('articles.show', array($article->id));
        }
    

      同时在 app/models/Article.php 添加 :

      protected $fillable = array('title', 'text');

      fillable 属性允许在动作中调用模型的 create 方法使用 title 和 text 属性。

      再次访问 http://localhost:8000/articles/create ,填写表单,还差一步就能创建文章了。

    5.7 显示文章

      和前面一样,我们要在 app/controllers/ArticlesController.php 文件中更改 show 动作,以及相应的视图文件。

      public function show($id)
      {
        $article = Article::find($id);
        return View::make('articles.show', compact('article'));
      }
    

      然后,新建 app/views/articles/show.blade.php 文件,写入下面的代码:

      <p>
        <strong>Title:</strong>
        {{ $article->title }}
      </p>
    
      <p>
        <strong>Text:</strong>
        {{ $article->text }}
      </p>
    

      做了以上修改后,就能真正的新建文章了。访问 http://localhost:8000/articles/create ,自己试试。

    5.8 列出所有文章

      我们还要列出所有文章,对应的路由是:

    GET|HEAD articles | articles.index | ArticlesController@index

      在 app/controllers/ArticlesController.php 文件中,修改 ArticlesController 控制器 index 动作:

        public function index()
        {
            $articles = Article::all();
            return View::make('articles.index', compact('articles'));
        }
    

      然后编写这个动作的视图,保存为 app/views/articles/index.blade.php:

    <h1>Listing articles</h1>
    
    <table>
      <tr>
        <th>Title</th>
        <th>Text</th>
      </tr>
    
      @foreach ($articles as $article)
        <tr>
          <td>{{ $article->title }}</td>
          <td>{{ $article->text }}</td>
        </tr>
      @endforeach
    </table>
    

      现在访问 http://localhost:8000/articles ,会看到已经发布的文章列表。

    5.9 添加链接

      至此,我们可以新建、显示、列出文章了。下面我们添加一些链接,指向这些页面。

      打开 app/views/welcome/index.blade.php 文件,添加:

      {{ link_to_route('articles.index', 'My Blog') }} 
    

      link_to_route 是 Laravel 内置的视图帮助方法之一,根据提供的文本和地址创建超链接。这上面这段代码中,地址是文章列表页面。

      接下来添加到其他页面的链接。先在 app/views/articles/index.blade.php 中添加“New Article”链接,放在标签之前:

      {{ link_to_route('articles.create', 'New article') }}
    

      点击这个链接后,会转向新建文章的表单页面。

      然后在 app/views/articles/create.blade.php 中添加一个链接,位于表单下面,返回到 index 动作:

      {{ link_to_route('articles.index', 'Back') }}
    

      最后,在 app/views/articles/show.blade.php 模板中添加一个链接,返回 index 动作,这样用户查看某篇文章后就可以返回文章列表页面了:

      {{ link_to_route('articles.index', 'Back') }}
    

    5.10 添加数据验证

      在 app/controllers/ArticlesController.php 文件中,修改 ArticlesController 控制器 store 动作:

        public function store()
        {
            $rules = array('title' => 'required|min:5');
    
            $validator = Validator::make(Input::all(), $rules);
    
            if ($validator->fails())
            {
                return Redirect::route('articles.create')
                    ->withErrors($validator)
                    ->withInput();
            }
    
            $article = Article::create(array('title'=>Input::get('title'), 'text'=>Input::get('text')));
    
            return Redirect::route('articles.show', array($article->id));
        }
    

      然后修改 app/views/articles/create.blade.php 添加 :

      @if ($errors->any())
      <div id="error_explanation">
          <h2>{{ count($errors->all()) }} prohibited
            this article from being saved:</h2>
          <ul>
          @foreach ($errors->all() as $message)
            <li>{{ $message }}</li>
          @endforeach
          </ul>
       </div>
      @endif
    

      再次访问 http://localhost:8000/articles/create ,尝试发布一篇没有标题的文章,会看到一个很有用的错误提示。

    5.11 更新文章

      我们已经说明了 CRUD 中的 CR 两种操作。下面进入 U 部分,更新文章。

      首先,要在 ArticlesController 中更改 edit 动作:

        public function edit($id)
        {
            $article = Article::find($id);
    
            return View::make('articles.edit', compact('article'));
        }
    

      视图中要添加一个类似新建文章的表单。新建 app/views/articles/edit.blade.php 文件,写入下面的代码:

    <h1>Editing Article</h1>
    
    @if ($errors->any())
    <div id="error_explanation">
        <h2>{{ count($errors->all()) }} prohibited
          this article from being saved:</h2>
        <ul>
        @foreach ($errors->all() as $message)
          <li>{{ $message }}</li>
        @endforeach
        </ul>
      </div>
    @endif
    
    {{ Form::open(array('route' => array('articles.update', $article->id), 'method' => 'put')) }}
        <p>
            {{ Form::text('title', $article->title) }}
        </p>
        <p>
            {{ Form::text('text', $article->text) }}
        </p>
        <p>
            {{ Form::submit('submit') }}
        </p>
    {{ Form::close() }}
    
    {{ link_to_route('articles.index', 'Back') }}
    

      这里的表单指向 update 动作

      method: put ( patch ) 选项告诉 Laravel,提交这个表单时使用 PUT 方法发送请求。根据 REST 架构,更新资源时要使用 HTTP PUT 方法。

      然后,要在 app/controllers/ArticlesController.php 中更新 update 动作:

        public function update($id)
        {
            $rules = array('title' => 'required|min:5');
    
            $validator = Validator::make(Input::all(), $rules);
    
            if ($validator->fails())
            {
                return Redirect::route('articles.create')
                    ->withErrors($validator)
                    ->withInput();
            }
    
            $article = Article::find($id);
    
            $article->title = Input::get('title');
            $article->text = Input::get('text');
            $article->save();
    
            return Redirect::route('articles.show', array($article->id));
        }
    

      最后,我们想在文章列表页面,在每篇文章后面都加上一个链接,指向 edit 动作。

      打开 app/views/articles/index.blade.php 文件,在“Show”链接后面添加“Edit”链接:

    <table>
      <tr>
        <th>Title</th>
        <th>Text</th>
        <th colspan="2"></th>
      </tr>
    
      @foreach ($articles as $article)
        <tr>
          <td>{{ $article->title }}</td>
          <td>{{ $article->text }}</td>
          <td>{{ link_to_route('articles.show', 'Show', $article->id) }}</td>
          <td>{{ link_to_route('articles.edit', 'Edit', $article->id) }}</td>
        </tr>
      @endforeach
    </table>
    

      我们还要在 app/views/articles/show.blade.php 模板的底部加上“Edit”链接:

      {{ link_to_route('articles.index', 'Back') }} |
      {{ link_to_route('articles.edit', 'Edit', $article->id) }}
    

    5.12 使用局部视图去掉视图中的重复代码

      编辑文章页面和新建文章页面很相似,显示错误提示的代码是相同的。下面使用局部视图去掉两个视图中的重复代码。

      新建 app/views/notifications.blade.php 文件,写入以下代码:

    @if ($errors->any())
    <div id="error_explanation">
        <h2>{{ count($errors->all()) }} prohibited
          this article from being saved:</h2>
        <ul>
        @foreach ($errors->all() as $message)
          <li>{{ $message }}</li>
        @endforeach
        </ul>
      </div>
    @endif
    

    下面来修改 app/views/articles/creat.blade.php 和 edit.blade.php 视图,使用新建的局部视图,把其中的上面代码全删掉,替换成:

    @include('notifications')
    

    5.13 删除文章

      现在介绍 CRUD 中的 D,从数据库中删除文章。按照 REST 架构的约定,删除文章的路由是:

    DELETE articles/{articles} | articles.destroy | ArticlesController@destroy

      删除资源时使用 DELETE 请求。如果还使用 GET 请求,可以构建如下所示的恶意地址:

      <a href='http://example.com/articles/1/destroy'>look at this cat!</a>
    

      删除资源使用 DELETE 方法,路由会把请求发往 app/controllers/ArticlesController.php 中的 destroy 动作。修改 destroy 动作:

        public function destroy($id)
        {
            Article::destroy($id);
    
            return Redirect::route('articles.index');
        }
    

      想把记录从数据库删除,可以在模型对象上调用 destroy 方法。注意,我们无需为这个动作编写视图,因为它会转向 index 动作。

      最后,在 index 动作的模板(app/views/articles/index.blade.php)中加上“Destroy”链接:

    <table>
      <tr>
        <th>Title</th>
        <th>Text</th>
        <th colspan="2"></th>
      </tr>
    
      @foreach ($articles as $article)
        <tr>
          <td>{{ $article->title }}</td>
          <td>{{ $article->text }}</td>
          <td>{{ link_to_route('articles.show', 'Show', $article->id) }}</td>
          <td>{{ link_to_route('articles.edit', 'Edit', $article->id) }}</td>
          <td>
            {{ Form::open(array('method' => 'DELETE', 'route' => array('articles.destroy', $article->id))) }}
              {{ Form::submit('Delete') }}
            {{ Form::close() }}
          </td>
        </tr>
      @endforeach
    </table>
    

    恭喜,现在你可以新建、显示、列出、更新、删除文章了。

    常见问题

    使用 Laravel 时,最好使用 UTF-8 编码存储所有外部数据。

    如果编码出错,常见的征兆是浏览器中显示很多黑色方块和问号。还有一种常见的符号是“ü”,包含在“ü”中。

    非 UTF-8 编码的数据经常来源于:

    • 你的文本编辑器:大多数文本编辑器(例如 TextMate)默认使用 UTF-8 编码保存文件。如果你的编辑器没使用 UTF-8 编码,有可能是你在模板中输入了特殊字符(例如 é),在浏览器中显示为方块和问号。这种问题也会出现在国际化文件中。默认不使用 UTF-8 保存文件的编辑器(例如 Dreamweaver 的某些版本)都会提供一种方法,把默认编码设为 UTF-8。记得要修改。
    • 你的数据库:默认情况下,Laravel 会把从数据库中取出的数据转换成 UTF-8 格式。如果数据库内部不使用 UTF-8 编码,就无法保存用户输入的所有字符。例如,数据库内部使用 Latin-1 编码,用户输入俄语、希伯来语或日语字符时,存进数据库时就会永远丢失。如果可能,在数据库中尽量使用 UTF-8 编码。

    转自:https://github.com/huanghua581/laravel-getting-started

  • 相关阅读:
    asp.net zero 8.2 学习-9-多租户设置,发送邮件配置
    asp.net zero 8.2 学习-8-实现在页面添加、编辑、删除、查看实体
    asp.net zero 8.2 学习-7-展示实体列表,实现查询,分页,过滤,排序功能
    asp.net zero 8.2 学习-6-权限控制
    asp.net zero 8.2 学习-5-实现增删改查服务及API测试
    asp.net zero 8.2 学习-4-创建接口及服务
    asp.net zero 8.2 学习-3-添加实体,并迁移到数据库
    asp.net zero 8.2 学习-2-创建一个页面
    asp.net zero 8.2 学习-1-安装
    .net core 3.1 jwt认证
  • 原文地址:https://www.cnblogs.com/linguoguo/p/3983404.html
Copyright © 2020-2023  润新知