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

  • 添加路由
Route::get('artiles', 'ArticlesController@index');
  • 建立控制器
php artisan make:controller ArticlesController --plain
  • 修改控制器
<?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;
    }

}

能夠在瀏覽器中看到返回的 JSON 結果,cool!php

修改控制器,返回視圖html

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

        return view('articles.index', compact('articles'));
    }

建立視圖laravel

@extends('layout')

@section('content')
    <h1>Articles</h1>

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

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

瀏覽結果,COOL!!!!瀏覽器

  • 顯示單個文章

添加顯示詳細信息的路由bash

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

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

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

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

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

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

        return view('articles.show', compact('article'));
    }

It's cool.code

新建視圖htm

@extends('layout')

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

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

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

修改index視圖

@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('ArticlesController@show', [$article->id])}}">{{$article->title}}</a>
                {{--還可使用--}}<br>
                <a href="{{url('/articles', $article->id)}}">{{$article->title}}</a>
            </h2>

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