创建一个index主页列出所有文章 生成路由 app/http/routes.php
route::get('/articles','articlescontroller@index');
生成一个controller php artisan make:controller articlescontroller
namespace app\http\controllers;use app\articles; //当你使用articles这个model的时候,phpstorme会帮你默认导入这个类use illuminate\http\request;use app\http\requests;class articlescontroller extends controller{ // public function index(){ //因为路由里面我们使用了articlescontroller@index,所以这里是index方法 $articles = articles::all(); //这里需要注意的是这个articles是我们创建的那个articles的model,在phpstorme会有提示,这里的all方法是返回这个model查询到的所有数据,这些数据是提前输入好的 return $articles; }}
访问localhost:8000/articles会出现以下内容,laravel会默认返回json格式的数据 本页json数据由fehelper进行自动格式化,若有任何问题,点击这里提交 意见反馈[{id: 1,title: title,content: content,publish_at: 2016-05-14 18:04:44,created_at: 2016-05-14 18:04:48,updated_at: 2016-05-14 18:04:48},{id: 2,title: title2,content: content2,publish_at: 2016-05-15 04:24:48,created_at: 2016-05-14 18:07:42,updated_at: 2016-05-14 18:07:42},{id: 3,title: second title,content: second content,publish_at: 2016-05-14 18:15:38,created_at: 2016-05-14 18:15:38,updated_at: 2016-05-14 18:15:38}]
运用已有的blade知识,配置一个layout 例如
resources/views/layout/app.blade.phplayout只是一个概念,这个文件主要是为了创造一个模板容器,用来处理那些可以复用的代码,例如一些html的head,body标签
laravel @yield('content')
@yield(('footer'))
创建刚才控制器指定的那个blade文件 resources/views/articles/index.blade.php
@extends('layout.app')@section('content') hello @foreach($articles as $article) //循环输出 {{$article->title}} {{$article->content}}
@endforeach@stop
创建一个文章页,列出单个文章 单个文章,需要有文章id在url里面区分,所以特意建立了一个新的路由和一个新的controller方法show
route::get('/articles/{id}','articlescontroller@show'); {id}传入变量参数,用大括号来标识,传入变量到controller的show方法
app/http/controllers/articlescontroller.php
class articlescontroller extends controller{ // public function index(){ $articles = articles::all();// return $articles; return view('articles.index',compact('articles')); } public function show($id){ //获取从路由传入的$id变量 $article = articles::find($id); //使用laravel提供的find方法查询数据库// return $articles; return view('articles.show',compact('article')); }}
resources/views/articles/show.blade.php
@extends('layout.app')@section('content') hello @foreach($articles as $article) {{--id}}>{{$article->title}}--}}{{-- id)}}>{{$article->title}}--}} id])}}>{{$article->title}} //这里有三种方法来传递变url量到blade中,第一种是直接写的,第二种是通过url方法,使用的路由方法,第三种是通过action方法,使用的是controller方式 {{$article->content}}
@endforeach@stop
本文由 peteryuan 创作,采用 署名-非商业性使用 2.5 中国大陆 进行许可。 转载、引用前需联系作者,并署名作者且注明文章出处。神一样的少年 » 实现简单blog展示(主要使用到eloquent和controller的结合)