
Application Post Part I
設定 routes
- 設定 404 page view
1 | @extends('layouts.app') |
- 新增 routes 在 admin group 裡面
Route::resource('admin/posts', 'AdminPostsController');
- 新增 Controller
php artisan make:controller --resource AdminPostsController
- 在 Controller 的 index
return view('admin.posts.index');
- 新增 /views/admin/posts/index.blade.php
1 | @extends('layouts.admin') |
- 修改 layouts 的連結
All Posts ->{{" {{route('admin.posts.index')" }}}}
Create Post ->{{" {{route('admin.posts.create')" }}}}
- 修改 Create 和 Edit 的 view
1 | @extends('layouts.admin') |
1 | @extends('layouts.admin') |
- 修改 Controller 的 create
return view('admin.posts.create');
Migration
- 新增 model
php artisan make:model Post -m
- 在 create_posts_table 新增欄位
1 | $table->integer('user_id')->unsigned()->index(); |
- 寫入資料庫
php artisan migrate
顯示貼文
- 在 Post model 處理 mass assignment
1 | protected $fillable = [ |
- 進入 tinker 模式新增資料庫內容
php artisan tinker
- 新增一行資料
$post = App\Post::create(['title'=>'my first post', 'body'=>'I love laravel with Edwin Diaz']);
- 修改 Controller 的 Index function
1 | $posts = Post::all(); |
- 在 Post index view 新增一個 table 讀取資料庫資料
1 | <table class="table"> |
Relationship 設定
- 在 User model 新增 posts function
1 | public function posts(){ |
- 在 Post model 新增 user function
1 | public function user(){ |
- 修改 index view 的 user 欄位
{{ "{{$post->user->name" }}}}
- 在 Post model 新增 photo 和 category function
1 | public function photo(){ |
- 在 Role model 讓 name 可寫入
1 | protected $fillable = [ |
創建表單
- 新增 create view 表單
1 | {!! Form::open(['method'=>'POST', 'action'=>'AdminPostsController@store', 'files'=>true]) !!} |
- 新增 Request
php artisan make:request PostsCreateRequest
- 修改 PostscreateRequest
1 | public function authorize() |
- 在 create post view include error message
@include('includes.form_error')
創建貼文
- 更新 Controller 的 store function
1 | $input = $request->all(); |
- 修改 Post index view 來顯示圖片
<img height="100" src="{{ "{{$post->photo ? $post->photo->file : 'http://placehold.it/400x400'" }}}}" alt="">