<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>
You can see the returned JSON results in the browser, cool!
Modify the controller and return to the view
<code> public function index() { $articles = Article::all(); return view('articles.index', compact('articles')); }</code>
Create View
<code>@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</code>
Browse the results, COOL! ! ! !
Add route showing details
<code>Route::get('articles/{id}', 'ArticlesController@show');</code>
Among them, {id}
is a parameter, indicating the id of the article to be displayed. Modify the controller:
<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 provides more convenient functions to modify the controller:
<code> public function show($id) { $article = Article::findOrFail($id); return view('articles.show', compact('article')); }</code>
It's cool.
New View
<code>@extends('layout') @section('content') <h1>{{$article->title}}</h1> <article> {{$article->body}} </article> @stop</code>
Try to access in your browser: /articles/1 /articles/2
Modify index view
<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('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</code>
The above introduces the basics of Laravel 5 (8) - the basic process of model, controller and view, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.