laravel(三):larave基本使用

1、基本视图显示


 

前文已经介绍如何创建控制器、动作和视图,下面我们来创建一些更实质的功能。

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

  • app/config/app.php 文件中的 debug 选项设置为 true (注:开启开发模式,更友好的开发提示);
  • app/config/database.php 文件中的 default 选项设置为 mysql(注:我们之前选择 mysql作为默认数据库);

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

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

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

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

 执行下面的命令,会看到定义了所有标准的 REST 动作

$ php artisan routes
+--------+-----------------------------------+------------------+----------------------------+----------------+---------------+
| 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 |                |               |
+--------+-----------------------------------+------------------+----------------------------+----------------+---------------+

根据自己创建的路由,使用前一节所说的命令生成控制器与视图。打开刚生成的 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 方法才能作为控制器的动作。

然后在文件 app/views/articles/create.blade.php中,写入如下代码

<h1>New Article</h1>

 最后在地址栏输入http://localhost:8000/articles/create , 可以看到页面中显示了一个标头。现在路由、控制器、动作和视图都能正常运行了。

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 动作。

表单写好了,路由也定义了,现在可以填写表单,然后点击提交按钮新建文章了。提交表单,会看到一个白屏。现在暂且不管这个错误。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 动作把表单提交的参数显示出来了。不过这么做没什么用,看到了参数又怎样,什么都没发生。

接下来需要创建模型

3、创建模型


和创建控制器、视图一样,创建模型也有相应的命令

$ php artisan make:model ModelsArticle

是不是特别简单,然后你会在app/models/Article.php文件中看到以下代码:

<?php

class Article extends Model {

}

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

如果想要指定数据库表名,插入如下代码:

protected $table = 'article';

到这里有没有感觉还缺点什么,对!就是缺少article,假如你还要去手动创建数据表,那你就low爆了,laravel为我们提供了migrate迁移命令,可以快速建表,节省时间。

4、运行迁移


使用 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、在控制器中保存数据


再回到 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 ,填写表单,还差一步就能创建文章了。

和前面一样,我们要在 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 ,自己试试。

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

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 ,会看到已经发布的文章列表。

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

打开 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') }}

6、添加数据验证


在 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 ,尝试发布一篇没有标题的文章,会看到一个很有用的错误提示。

7、


我们已经说明了 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) }}

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


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

新建 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')

9、最后来个删除吧


现在介绍 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开发中难免会遇到问题,需要协助可以使用这些资源:

https://laravel-china.org/

http://www.golaravel.com/

http://laravelacademy.org/

原文地址:https://www.cnblogs.com/lxlry/p/6236060.html