首頁  >  文章  >  後端開發  >  Laravel 5 基礎(八)- 模型、控制器、視圖基礎流程

Laravel 5 基礎(八)- 模型、控制器、視圖基礎流程

WBOY
WBOY原創
2016-08-08 09:26:47807瀏覽
  • 添加路由
<code>Route::get('artiles', 'ArticlesController@index');</code>
  • 建立控制器
<code> php artisan make:controller ArticlesController --plain</code>
  • 修改控制器
<code><?php namespace App\Http\Controllers;

use App\Article;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class ArticlesController extends Controller {

	public function index() {
        $articles = Article::all();

        return $articles;
    }

}</code>

可以在瀏覽器中看到返回的 JSON 結果,cool!

修改控制器,返回視圖

<code>	public function index() {
        $articles = Article::all();

        return view(&#39;articles.index&#39;, compact(&#39;articles&#39;));
    }</code>

建立視圖

<code>@extends(&#39;layout&#39;)

@section(&#39;content&#39;)
    <h1>Articles</h1>

    @foreach($articles as $article)
        <article>
            <h2>{{$article->title}}</h2>

            <div class="body">{{$article->body}}</div>
        </article>
    @endforeach
@stop</code>

瀏覽結果,COOL! ! ! !

  • 顯示單一文章

新增顯示詳細資訊的路由

<code>Route::get('articles/{id}', 'ArticlesController@show');</code>

其中,{id} 是參數,表示要顯示的文章的 id,修改控制器:

<code>    public function show($id) {
        $article = Article::find($id);

        //若果找不到文章
        if (is_null($article))
        {
            //生产环境 APP_DEBUG=false
            abort(404);
        }
        return view('articles.show', compact('article'));
    }</code>

laravel 提供了更方便的功能,修改控制器:

<code>    public function show($id) {
        $article = Article::findOrFail($id);

        return view('articles.show', compact('article'));
    }</code>

It's cool.

新視圖

<code>@extends('layout')

@section('content')
    <h1>{{$article->title}}</h1>

    <article>
        {{$article->body}}
    </article>
@stop</code>

在瀏覽器中嘗試訪問:/articles/1 /articles/2

修改index視圖

<code>@extends('layout')

@section('content')
    <h1>Articles</h1>
    <hr/>
    @foreach($articles as $article)
        <article>
            <h2>
                {{--这种方式可以--}}
                <a href="/articles/{{$article->id}}">{{$article->title}}</a>
                {{--这种方式更加灵活,不限制路径--}}<br>
                <a href="{{action(&#39;ArticlesController@show&#39;, [$article->id])}}">{{$article->title}}</a>
                {{--还可以使用--}}<br>
                <a href="{{url(&#39;/articles&#39;, $article->id)}}">{{$article->title}}</a>
            </h2>

            <div class="body">{{$article->body}}</div>
        </article>
    @endforeach
@stop</code>

以上就介紹了Laravel 5 基礎(八)- 模型、控制器、視圖基礎流程,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn