laravel(三):larave基本使用

一、基本视图显示


 

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

在此以前咱们须要修改一些配置:mysql

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

在博客程序中,咱们要建立一个新“资源”。资源是指一系列相似的对象,好比文章,人和动物。laravel

资源能够被建立、读取、更新和删除,这些操做简称 CRUD。sql

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

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

 执行下面的命令,会看到定义了全部标准的 REST 动做架构

$ php artisan routes

根据本身建立的路由,使用前一节所说的命令生成控制器与视图。打开刚生成的 app/controllers/ArticlesController.php 文件,控制器就是一个类,继承自 BaseController。在这个 ArticlesController 类中定义了对应的资源动做。动做的做用是处理文章的 CRUD 操做。
修改 ArticlesController.php 文件中的+--------+-----------------------------------+------------------+----------------------------+----------------+---------------+ | 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 | | | +--------+-----------------------------------+------------------+----------------------------+----------------+---------------+
public function create()
    {
        //
    }

 为app

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

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

而后在文件 app/views/articles/create.blade.php中,写入以下代码ui

<h1>New Article</h1>

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

 

二、首个表单


要在模板中编写表单,可使用“表单构造器”。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 动做把表单提交的参数显示出来了。不过这么作没什么用,看到了参数又怎样,什么都没发生。

接下来须要建立模型

 

三、建立模型


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

$ php artisan make:model Models\Article

 

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

<?php

class Article extends Model {

}

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

若是想要指定数据库表名,插入以下代码:

protected $table = 'article';

 

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

 

四、运行迁移


使用 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 Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

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

 

五、在控制器中保存数据


再回到 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') }}

 

六、添加数据验证


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

 

七、


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

 

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


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

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

 

九、最后来个删除吧


如今介绍 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/

相关文章
相关标签/搜索