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

來源:互聯網
上載者:User
  • 添加路由
Route::get('artiles', 'ArticlesController@index');
  • 建立控制器
 php artisan make:controller ArticlesController --plain
  • 修改控制器

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

修改控制器,返回視圖

public function index() { $articles = Article::all(); return view('articles.index', compact('articles')); }

建立視圖

@extends('layout')@section('content') 

Articles

@foreach($articles as $article)

{{$article->title}}

{{$article->body}} @endforeach@stop

瀏覽結果,COOL!!!!

  • 顯示單個文章

添加顯示詳細資料的路由

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

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

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

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

 public function show($id) { $article = Article::findOrFail($id); return view('articles.show', compact('article')); }

It's cool.

建立視圖

@extends('layout')@section('content') 

{{$article->title}}

{{$article->body}} @stop

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

修改index視圖

@extends('layout')@section('content') 

Articles

@foreach($articles as $article)

{{--這種方式可以--}} id}}">{{$article->title}} {{--這種方式更加靈活,不限制路徑--}}
id])}}">{{$article->title}} {{--還可以使用--}}
id)}}">{{$article->title}}

{{$article->body}} @endforeach@stop

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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.