Reference:laravel.com
以下將實作一個留言版有會員系統,以及可以新增顯示刪除留言,且知道如何只看到自己的留言
目錄
- Environment 環境
- Database 資料庫
- Routing 路由
- Layouts & Views
- Create 新增
- Read 讀取
- Delete 刪除
- Review 後記
- 到底端
- Environment 環境
安裝 Laravel
規則 # composer create-project --prefer-dist [<package>] [<directory>] [<version>]
# composer create-project --prefer-dist laravel/laravel guestbook
測試看看可不可以跑:P
# cd guestbook
# php artisan serve
.env檔
記得先去mysql新增一個資料庫(guestbook)
.env1 2 3
| DB_DATABASE=guestbook DB_USERNAME=自訂 DB_PASSWORD=自訂
|
- Database 資料庫
資料表 Table
我們將需要users
資料表和messages
資料表
laravel已經幫我們弄好users資料表的migration
所以我們只要製作messages資料表的migration
# php artisan make:migration create_messages_table --create=messages
以上兩個遷移檔都在database/migrations
中可以找到
讓我們在messages新增兩個欄位:用來跟user做關聯與留言內容
time_create_messages_table.php1 2 3 4 5 6 7 8 9
| public function up() { Schema::create('messages', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->index(); // 新增 $table->string('name'); // 新增 $table->timestamps(); }); }
|
好了之後執行
# php artisan migrate
可以打開你的database檢查看看guestbook資料庫有了users
資料表和messages
資料表
Model 模型 (Eloquent Model)
一般來說一個model對應一張資料表
laravel已經幫我們弄好User Model(app/User.php
)
所以我們只要
# php artisan make:model Message
Message.php就這樣出現了(app/Message.php
)
讓我們在Message model新增讓name
欄位能夠被mass-assignable(批量賦值,再使用model的create
方法時能夠填入name
)
使用$fillable
app/Message.php1 2 3 4 5 6 7 8 9 10
| <?php namespace App; use Illuminate\Database\Eloquent\Model; class Message extends Model { protected $fillable = ['name']; // 新增 }
|
關聯 Relationship (Eloquent Relationships)
首先我們要知道一個User可以多個Message,而一篇Message則只有一個User
messages
關聯
app/User.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <?php namespace App; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { // 其他的 Eloquent 屬性(非重點) // 新增,可以取得該user的所有message。 public function messages() { return $this->hasMany(Message::class); } }
|
users
關聯
app/Message.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <?php namespace App; use Illuminate\Database\Eloquent\Model; class Message extends Model { protected $fillable = ['name']; // 新增,取得此篇message撰寫之user public function user() { return $this->belongsTo(User::class); } }
|
有了關聯我們就能靈活運用例如下:
1 2 3 4 5
| $user = App\User::find(1); foreach ($user->messages as $message) { echo $message->name; }
|
- Routing 路由
View 視圖
以下預設的程式碼回傳的view就是laravel的歡迎頁面
可以在resources/views
中看到,我們待會再來弄這些檔案
app/Http/routes.php1 2 3
| Route::get('/', function () { return view('welcome'); });
|
Authentication 認證
Laravel都寫好了
定義在app/Http/Controllers/Auth/AuthController.php
中
那我們要寫啥呢? 答案就是:註冊+登入的模板和指向AuthController的路由
但Laravel 5.2提供了以下方法
# php artisan make:auth --views
(–views 代表只幫我們相關新增view)
差在幫你
1 2 3
| Route::auth(); Route::get('/home', 'HomeController@index'); 還有製造HomeController
|
在resources/views
產生了auth/一堆檔案
、layout/app.blade.php
、home.blade.php
、welcome.blade.php
在app/Http/routes.php
加入這行
它的功能可以在/vendor/laravel/framework/src/Illuminate/Routing/Router.php
中看見
/vendor/laravel/framework/src/Illuminate/Routing/Router.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public function auth() { // Authentication Routes... $this->get('login', 'Auth\AuthController@showLoginForm'); $this->post('login', 'Auth\AuthController@login'); $this->get('logout', 'Auth\AuthController@logout'); // Registration Routes... $this->get('register', 'Auth\AuthController@showRegistrationForm'); $this->post('register', 'Auth\AuthController@register'); // Password Reset Routes... $this->get('password/reset/{token?}', 'Auth\PasswordController@showResetForm'); $this->post('password/email', 'Auth\PasswordController@sendResetLinkEmail'); $this->post('password/reset', 'Auth\PasswordController@reset'); }
|
Message Controller
# php artisan make:controller MessageController
這個檔案會放在app/Http/Controllers
中
app/Http/routes.php1 2 3
| Route::get('/messages', 'MessageController@index'); Route::post('/message', 'MessageController@store'); Route::delete('/message/{message}', 'MessageController@destroy');
|
我們現在需要讓user登入之後才可以發message
為了要讓所有MessageController的行為(新增修改刪除)要有認證才能用
可以在constructor(建構子)增加middleware method的呼叫
ps.可用的增加middleware
都定義再app/Http/Kernel.php
app/Http/Controller/MessageController.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class MessageController extends Controller { // 新增 public function __construct() { $this->middleware('auth'); } }
|
- Layouts & Views
Layout
還記得# php artisan make:auth --views
這個指令嗎?他幫我們寫完Layout了
如果不喜歡就讓我們砍掉重練layout吧,範例中有引入bootstrap跟jquery
別的頁面的內容可以寫在@yield('content')
中
resources/views/layouts/app.blade.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <!DOCTYPE html> <html lang="en"> <head> <title>Laravel Guestbook</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> </head> <body> <div class="container"> <nav class="navbar navbar-default"> I'm Navbar </nav> </div> @yield('content') </body> </html>
|
Views
接下來產生建立留言的表單跟列出所有留言的view吧
引用語法是@extends('layouts.app')
,@section('content')
及 @endsection
resources/views/messages/index.blade.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| @extends('layouts.app') @section('content') <div class="panel-body"> @include('common.errors') <form action="{{ url('message') }}" method="POST" class="form-horizontal"> {{ csrf_field() }} <div class="form-group"> <label for="message-name" class="col-sm-3 control-label">請輸入</label> <div class="col-sm-6"> <input type="text" name="name" id="message-name" class="form-control"> </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-default"> <i class="fa fa-plus"></i> 留言 </button> </div> </div> </form> </div> @endsection
|
接著讓我們在MessageController
的index
方法回傳此view
app/Http/Controller/MessageController.php1 2 3 4 5 6 7 8 9 10
| /** * Display a list of all of the user's message. * * @param Request $request * @return Response */ public function index(Request $request) { return view('messages.index'); }
|
那我們現在只需要POST /message
route’s controller method來處理表單輸入的內容
- Create 新增
Validation 驗證
我們繼續新增MessageController@store
來驗證表單輸入的內容
規定name
欄位為必填及少於255字
我們可以使用controller內建的ValidatesRequests
trait
它提供了validate
method,接收一個request和驗證規則的陣列
app/Http/Controller/MessageController.php1 2 3 4 5 6 7 8 9 10 11 12 13 14
| /** * Create a new message. * * @param Request $request * @return Response */ public function store(Request $request) { $this->validate($request, [ 'name' => 'required|max:255', ]); //待新增 : Create The Message... }
|
$errors Variable
這個$errors變數可以用在所有的view中~
還記得我們在view中使用了@include('common.errors')
讓我們新增這個檔案
resources/views/common/errors.blade.php1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @if (count($errors) > 0) <!-- 表單錯誤清單 --> <div class="alert alert-danger"> <strong>Whoops! Something went wrong!</strong> <br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif
|
Create Message!
現在驗證輸入已經完畢~返回到我們的主題-新增
laravel為relationship提供create
方法,會接收一個陣列並自動設置foreign key
使用$request->user()
得到目前的使用者,會被create
自動填入user_id
app/Http/Controller/MessageController.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| /** * Create a new message. * * @param Request $request * @return Response */ public function store(Request $request) { $this->validate($request, [ 'name' => 'required|max:255', ]); $request->user()->messages()->create([ 'name' => $request->name, ]); return redirect('/messages'); }
|
- Read 讀取
Displaying Messages!
我們現在要顯示所有留言,因此需使用MessageController@index
方法
view
函式第二個參數(array)可以在view中使用
app/Http/Controller/MessageController.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| /** * Display a list of all of the user's message. * * @param Request $request * @return Response */ public function index(Request $request) { // 等同於$messages = Message::where('user_id', $request->user()->id)->get(); $messages = $request->user()->messages()->get(); return view('messages.index', [ 'messages' => $messages, ]); }
|
Dependency Injection 依賴注入
我們將注入MessageRepository
至我們的MessageController
,透過它存取所有的資料
1.首先先建立資源庫(Creating The Repository)
定義一個 MessageRepository
存放所有 Message model
的資料存取邏輯
我們建立 app/Repositories
目錄,並增加MessageRepository
Class
app/Repositories/MessageRepository.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <?php namespace App\Repositories; use App\User; class MessageRepository { /** * Get all of the messages for a given user. * * @param User $user * @return Collection */ public function forUser(User $user) { return $user->messages() ->orderBy('created_at', 'asc') ->get(); /** 這樣也可 *return Message::where('user_id', $user->id) * ->orderBy('created_at', 'asc') * ->get(); */ } }
|
2.注入資源庫(Injecting The Repository)
資源庫已經定義好於是,
在 MessageController
的constructor中對它使用type-hint(型別提示),並在我們的 index route中使用
app/Http/Controller/MessageController.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| <?php namespace App\Http\Controllers; use App\Http\Requests; use Illuminate\Http\Request; use App\Message; // 新增 use App\Repositories\MessageRepository; // 新增 class MessageController extends Controller { /** * The repository instance. * * @var MessageRepository */ protected $messages; /** * Create a new controller instance. * * @param MessageRepository $messages * @return void */ public function __construct(MessageRepository $messages) // 新增 { $this->middleware('auth'); $this->messages = $messages; // 新增 } /** * Display a list of all of the user's message. * * @param Request $request * @return Response */ public function index(Request $request) { return view('messages.index', [ 'messages' => $this->messages->forUser($request->user()), ]); } }
|
Displaying Messages
resources/view/messages/index.blade.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| @extends('layouts.app') @section('content') <!-- 已完成:建立留言 --> <!-- 顯示目前留言 --> @if (count($messages) > 0) <div class="panel panel-default"> <div class="panel-heading"> Current Messages </div> <div class="panel-body"> <table class="table table-striped message-table"> <!-- Table Headings --> <thead> <th>Content</th> <th> </th> </thead> <!-- Table Body --> <tbody> @foreach ($messages as $message) <tr> <!-- Message Name --> <td class="table-text"> <div>{{ $message->name }}</div> </td> <td> <!-- 未完成:刪除按鈕 --> </td> </tr> @endforeach </tbody> </table> </div> </div> @endif @endsection
|
現在可以顯示留言跟新增留言嚕~~
只剩下刪除功能
- Delete 刪除
增加刪除按鈕
1 2
| 這邊`action="{{ url('message/'.$message->id) }}"` 就是 `action="/message/{{ $message->id }}"`的意思 我們為了要在route使用delete,所以加了`{{ method_field('DELETE') }}`,但不加用post也是可~
|
resources/view/messages/index.blade.php1 2 3 4 5 6 7 8 9 10 11
| <!-- Delete Button --> <td> <form action="{{ url('message/'.$message->id) }}" method="POST"> {!! csrf_field() !!} {!! method_field('DELETE') !!} <button type="submit" id="delete-message-{{ $message->id }}" class="btn btn-danger"> <i class="fa fa-btn fa-trash"></i>Delete </button> </form> </td>
|
Route Model Binding
觀察一下
route中的{message}跟controller中的$message是相符的
Laravel 5.2的implicit model binding
(隱式模型綁定)會自動注入對應的model instance
讓我們新增delete route和delete method=destroy
1 2 3 4 5 6 7 8
| Route::delete('/message/{message}', 'MessageController@destroy'); 跟 public function destroy(Request $request, Message $message) { $message->delete(); return redirect('/messages'); }
|
Authorization 認證
我們要防止壞蛋隨機亂傳/message/{message}
URL來亂刪留言
Laravel 使用 Policy
來授權,一般一個policy會對應置一個model
讓我們下指令
php artisan make:policy MessagePolicy
並更改產生的檔案
增加一個destroy function,簡單的檢查當使用者的 ID 符合message的 user_id
ps.所有的Policy都必須回傳ture或false
app/Policies/MessagePolicy.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <?php namespace App\Policies; use Illuminate\Auth\Access\HandlesAuthorization; use App\User; // 新增 use App\Message; // 新增 class MessagePolicy { use HandlesAuthorization; /** * Create a new policy instance. * * @return void */ public function __construct() { // } // 新增 public function destroy(User $user, Message $message) { return $user->id === $message->user_id; } }
|
讓我們來連接 Message Model
與 MessagePolicy
這會告訴 Laravel,每當我們嘗試授權 Message instance的行為時該用哪個policy:
app/Providers/AuthServiceProvider.php1 2 3 4 5 6 7
| protected $policies = [ 'App\Message' => 'App\Policies\MessagePolicy', // 新增 ]; 或 protected $policies = [ Message::class => MessagePolicy::class, // 新增 ];
|
現在我們policy已經寫完了,讓我們去controller的destroy使用他
authorize
method的第一個參數是我們希望呼叫的policy
method名,第二個參數是model
ps.所有Laravel的controller可呼叫 authorize
method(AuthorizesRequest trait提供)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| /** * Destroy the given message. * * @param Request $request * @param Message $message * @return Response */ public function destroy(Request $request, Message $message) { $this->authorize('destroy', $message); $message->delete(); return redirect('/messages'); }
|
- Review 後記
你做到了:P
接下來是雜項~可以不理我XD
完整Layout
加些完整的東西到resources/view/messages/index.blade.php
吧
resources/view/messages/index.blade.php1 2 3 4 5 6 7 8 9 10 11 12 13
| <div class="container"> <div class="col-sm-offset-2 col-sm-8"> <div class="panel panel-default"> <div class="panel-heading"> New Message </div> ... ... </div> ... ... </div> </div>
|
只有自己能看到
記住這是個只看得到自己留言的留言版
如果想要顯示大家的留言可以這樣做
讓$messages不篩選user_id
app/Http/Controller/MessageController.php1 2 3 4 5 6 7
| public function index() { $messages = Message::all(); return view('messages.index', [ 'messages' => $messages, ]); }
|
再去view改成只有自己的留言有刪除按鈕就好
resources/view/messages/index.blade.php1 2 3
| @if (Auth::user()->id==$message->user_id) <!-- Delete Button> @endif
|
顯示單一留言詳細內容
只要加上一些就可以嚕
1 2 3 4 5 6 7 8 9
| Route::get('messages/{message}', 'MessageController@show'); public function show(Message $message)//$id) { //$message = Message::find($id); return $message; } <a href="{{ url('messages/'.$message->id) }}"><div>{{ $message->name }}</div></a>
|
新增留言的回覆
Database&Model
php artisan make:migration create_notes_table --create=notes
migration file1 2
| $table->integer('message_id')->unsigned()->index(); $table->text('body');
|
# php artisan migrate
php artisan make:model Note
Note.php1 2 3 4 5
| protected $fillable = ['body']; public function message() { return $this->belongsTo(Message::class); }
|
Message.php1 2 3 4
| public function notes() { return $this->hasMany(Note::class); // Note::class=App\Note }
|
Route&Controller
route.php1
| Route::post('messages/{message}/notes', 'NotesController@store');
|
php artisan make:controller NotesController
NotesController1 2 3 4 5 6 7 8 9
| use App\Message; use App\Note; public function store(Request $request, Message $message) { $message->notes()->create([ 'body' => $request->body ]); return back(); }
|
View
resources/messages/show.blade.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="breadcrumb">{{ $message->name }}</div> <ul class="list-group"> @foreach ($message->notes as $note) <li class="list-group-item">{{ $note->body }}</li> @endforeach </ul> <form method="POST" action="/messages/{{ $message->id}}/notes"> {{ csrf_field() }} <div class="form-group"> <textarea name="body" class="form-control"></textarea> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">Add Comment</button> </div> </form> </div> </div> </div> @endsection
|
編輯留言
Route::get('messages/{message}/edit','MessageController@edit');
index.blade.php1 2 3 4 5 6 7 8 9 10
| <!-- Edit Button --> <td> @if (Auth::user()->id==$message->user_id) <form action="{{ url('messages/'.$message->id.'/edit') }}" method="GET"> <button type="submit" id="edit-message-{{ $message->id }}" class="btn btn-info"> <i class="fa fa-pencil fa-fw"></i>Edit </button> </form> @endif </td>
|
MessageController1 2 3 4
| public function edit(Message $message) { return view('messages.edit',compact('message')); }
|
edit.blade.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="breadcrumb">Origin Message: {{ $message->name }}</div> <form method="POST" action="{{ url('messages/'.$message->id) }}"> {{ csrf_field() }} {{ method_field('PATCH') }} <div class="form-group"> <textarea name="body" class="form-control">{{ $message->name }}</textarea> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">Update Comment</button> </div> </form> </div> </div> </div> @endsection
|
Route::patch('messages/{message}', 'MessageController@update');
MessageController1 2 3 4 5 6 7 8 9
| public function update(Request $request, Message $message) { $this->authorize('update', $message); $message->update([ 'name' => $request->name ]); return redirect('/messages'); }
|
app/Policies/MessagePolicy.php1 2 3
| public function update(User $user, Message $message){ return $user->id === $message->user_id; }
|
Ajax新增留言
resources/views/layouts/app.blade.php1 2 3
| <meta name="csrf-token" content="{{ csrf_token() }}" /> @yield('css') @yield('js')
|
resources/views/messages/index.blade.php1 2 3 4 5 6 7
| @section('js') <script src='{{ asset("js/index.js") }}'></script> @endsection <button id="ajax" class="btn btn-default" style="float:right"><i class="fa fa-plus"></i>Ajax留言</button> <tbody id="ajax-append">
|
js/index.js1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| $(function(){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('#ajax').click(function() { $.ajax({ url: "/message", data: { name: $("#message-name").val() }, type: "POST", dataType: "json", success: function(data,statusTxt,xhr) { $('#ajax-append').append("<tr><td class='table-text'><a href=messages/"+data.id+"><div>"+data.message+"</div></a></td><td></td><td></td></tr>"); }, error: function() { console.log("fail"); }, complete: function() { } }); }); });
|
MessageController@store1 2 3 4 5 6 7 8
| $message = Message::orderby('created_at','desc')->first(); $response = array( 'id' => $message->id, 'message' => $message->name ); if($request->ajax()){ return response()->json($response); }
|
雜1 2 3 4 5 6 7
| // $('#...').submit(... // event.preventDefault(); // 阻止元素發生默認的行為,當點擊提交按鈕時阻止表單提交)。 $("#form id").find(":text,textarea").each(function() { $(this).val(""); }); // :text 是 type selector , textarea是標籤 // 會選到很多個所以each每一個
|
回覆關聯user_id,並且eager-load
create_notes_table.php1
| $table->integer('user_id')->unsigned()->index();
|
php artisan migrate:refresh
app/Note.php1 2 3 4 5 6
| protected $fillable = ['body','user_id']; public function user() { return $this->belongsTo(User::class); }
|
NotesController@store1 2 3 4 5
| $message->notes()->create([ 'body' => $request->body 'body' => $request->body, 'user_id' => $request->user()->id ]);
|
MessageController@show1 2
| //$message = Message::with('notes.user')->find(1); $message->load('notes.user');
|
class="pull-right" === style="float:right"
resources/views/messages/show.blade.php1 2 3
| <a href="#" class="pull-right">{{ $note->user->name }}</a> <textarea name="body" class="form-control">{{ old('body') }}</textarea>
|
Seed 製作留言
php artisan make:seeder MessagesTableSeeder
database\seeds\MessagesTableSeeder.php
MessagesTableSeeder.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public function run() { // 新增前清空 // DB::table('{資料表名稱}')->truncate(); // OR \App\Message::truncate(); // factory(\App\Message::class,5)‐>create(); (database\factories\ModelFactory.php) // OR 以下 $faker = \Faker\Factory::create('zh_TW'); // 假資料 foreach(range(1, 5) as $number) { $rand=rand(0,1); \App\Message::create([ 'name' => $number.'-fake:'.$faker->word.'rand: '.$rand, 'created_at' => \Carbon\Carbon::now()->addDays($number) ]); } }
|
$ php artisan db:seed --class=MessagesTableSeeder
OR
database\seeds\DatabaseSeeder.php1 2 3 4 5 6 7 8 9 10
| use Illuminate\Database\Eloquent\Model; class DatabaseSeeder extends Seeder { public function run() { Model::unguard(); $this->call(MessagesTableSeeder::class); Model::reguard(); } }
|
$ php artisan db:seed
php artisan make:request MessageRequest
authorize(授權) // 身分
rules(驗證規則) // 內容
app\Http\Requests\MessageRequest.php1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public function authorize() { // Route::post('message/{id}'); $id = $this->route('id'); // 檢查這個 Message 是不是這個 user 新增的? return Message::where('id', $id)->where('user_id', \Auth::id())->exist(); } public function rules() { return [ 'body' => 'require' ]; }
|
1 2 3 4
| use App\Http\Requests\MessageRequest; public function update(MessageRequest $request){ 執行至此表式通過驗證 }
|