// routes.php
Route::get('articles', 'ArticlesController@index');
Route::get('articles/{id}', 'ArticlesController@show');
php artisan make:controller ArticlesController --plain
--plain 生成空控制器,避免多餘 RESTful 方法。
namespace App\Http\Controllers;
use App\Article;
use App\Http\Controllers\Controller;
class ArticlesController extends Controller {
public function index() {
$articles = Article::all();
return view('articles.index', compact('articles'));
}
public function show($id) {
$article = Article::findOrFail($id); // 404 自動拋出
return view('articles.show', compact('article'));
}
}
resources/views/articles/index.blade.php
@extends('layout')
@section('content')
<h1>Articles</h1><hr/>
@foreach($articles as $article)
<article>
<h2>
<a href="{{ action('ArticlesController@show', [$article->id]) }}">
{{ $article->title }}
</a>
</h2>
<div class="body">{{ $article->body }}</div>
</article>
@endforeach
@stop
resources/views/articles/show.blade.php
@extends('layout')
@section('content')
<h1>{{ $article->title }}</h1>
<article>{{ $article->body }}</article>
@stop
| 方法 | 示例 | 優缺點 |
|---|---|---|
| 硬編碼 | /articles/{{$article->id}} | 簡單但路徑變更需全量替換 |
| action() | action('ArticlesController@show', [$article->id]) | 綁定控制器方法,重構友好 |
| url() | url('/articles', $article->id) | 基於路由前綴,靈活 |
推薦使用 route()(需命名路由)或 action(),避免硬編碼。
Article::all() 返回 Collection,自動轉 JSON 或供視圖遍歷。findOrFail() 找不到拋出 ModelNotFoundException,Laravel 自動轉 404。compact('articles') 等同 ['articles' => $articles],簡潔傳遞多變量。@extends/@section/@yield 實現佈局復用。Laravel MVC 基礎流程:路由分發 → 控制器協調 → 模型查詢 → 視圖渲染。掌握此流程是進階學習表單驗證、授權、API 資源等功能的基石。