เริ่มจากเตรียม Database ก่อนโดยเราจะใช้ตารางที่ชื่อ blogs โดยดูการสร้างจากหัวข้อนี้ laravel 5.4 การใช้งาน MIGRATIONS และ SEEDING
โดยเข้าไปในโฟลเดอร์ app\Models หากไม่มีโฟลเดอร์ Models ก็ให้สร้างขึ้นมา แล้วสร้างไฟล์ชื่อ Blog.php ใว้ในโฟลเดอร์ Models
* การตั้งชื่อไฟล์จะใช้ชื่อตารางโดยตัด(s)ออก เช่น ตารางชื่อ blogs ก็จะตั้งชื่อเป็น Blog.php แต่หากจะตั้งแบบอื่นก็ได้ แล้วระบุชื่อตารางที่ต้องการ เช่น
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Flight extends Model { /** * The table associated with the model. * * @var string */ protected $table = 'blogs'; } |
มาเขียนต่อครับ ในไฟล์ Blog.php ให้เพิ่มโค๊ดดังนี้
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Blog extends Model { /** * The table associated with the model. * * @var string */ } |
เราก็จะได้ Eloquent Model ที่ลิ้งค์กับตาราง blogs โดยสามารถเข้าถึงจาก Controllers ได้
โดยใช้ resource controller (ดูเพิ่มเติม) ใช้คำสั่ง Command Prompt ด้านล่างเพื่อสร้าง
1 |
php artisan make:controller BlogController --resource |
หรือเข้าไปในโฟลเดอร์ app\Http\Controllers แล้วสร้างไฟล์ชื่อ BlogController.php ในไฟล์เขียนโค๊ดดังนี้
1 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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class BlogController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } |
เนื่องจากเราสร้าง Model Blog ใว้ในโฟลเดอร์ app/Models ดังนั้นเราจึงต้องบอกให้ Controller รู้ว่าเราจะใช้ app/Models/Blog โดยกำหนด use App\Models\Blog; ใว้ที่ด้านบนของ Controller ดังนี้
1 2 3 4 5 6 7 8 9 10 |
<?php namespace App\Http\Controllers; use App\Models\Blog; use Illuminate\Http\Request; class BlogController extends Controller { ..... |
เปิดไฟล์ routes/web.php แล้วเพิ่มโค๊ดดังนี้
1 |
Route::resource('blogs', 'BlogController'); |
โดยระบบจะกำหนด URL และ Action ในการ Creating, reading, updating, and deleting ให้อัตโนมัติ ตามตารางด้านล่าง
HTTP Verb | Path (URL) | Action (Method) | Route Name |
GET | /blogs | index | blogs.index |
GET | /blogs/create | create | blogs.create |
POST | /blogs | store | blogs.store |
GET | /blogs/{id} | show | blogs.show |
GET | /blogs/{id}/edit | edit | blogs.edit |
PUT/PATCH | /blogs/{id} | update | blogs.update |
DELETE | /blogs/{id} | destroy | blogs.destroy |
*สามารถกำหนดใช้เฉพาะบาง Action ใน Routes ได้ เช่น
1 2 3 4 5 6 7 |
Route::resource('blogs', 'BlogController', ['only' => [ 'index', 'show' ]]); Route::resource('blogs', 'BlogController', ['except' => [ 'create', 'store', 'update', 'destroy' ]]); |
ให้สร้าง view เพื่อใช้แสดงผลข้อมูลดังนี้
resources
Description | URL | Controller Function | View File |
Default page for showing all the blogs. | GET example.com/blogs | index() | resources/views/blogs/index.blade.php |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php ... /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // get all the blogs $blogs = Blog::all()->sortByDesc('created_at'); // load the view and pass the user return View('blogs.index') ->with('blogs', $blogs); } ... |
1 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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}" /> <meta name="description" content=""> <meta name="author" content=""> <title> {{ config('app.name', 'Laravel') }}</title> <!-- Bootstrap Core CSS --> <link href="{{ asset('/assets/vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet"> </head> <body> <div class="container"> <div class="row page-header"> <div class="col-xs-12 col-md-6 col-lg-6"> <h1>Blogs</h1> </div> <div class="col-xs-12 col-md-6 col-lg-6"> <a href="{{ URL('/blogs/create') }}" class="btn btn-default pull-right"><i class="fa fa-plus"></i> Create Blog</a> </div> </div> <!-- /.row --> <!-- will be used to show any messages --> @if (Session::has('message')) <div class="alert alert-success">{{ Session::get('message') }}</div> @endif <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead> <tr> <td>Title</td> <td>Content</td> <td>Created time</td> <td>Actions</td> </tr> </thead> <tbody> @foreach($blogs as $key => $value) <tr> <td>{{ $value->title }}</td> <td>{{ $value->content }}</td> <td>{{ $value->created_at }}</td> <!-- we will also add show, edit, and delete buttons --> <td> <!-- delete the nerd (uses the destroy method DESTROY /blogs/{id} --> <!-- we will add this later since its a little more complicated than the other two buttons --> <form class="form-horizontal" method="POST" action="{{ URL('blogs/'.$value->id) }}"> {{ csrf_field() }} {{ method_field('DELETE') }} <!-- show the nerd (uses the show method found at GET /users/{id} --> <a class="btn btn-xs btn-success" href="{{ URL::to('blogs/' . $value->id) }}">Show</a> <!-- edit this nerd (uses the edit method found at GET /users/{id}/edit --> <a class="btn btn-xs btn-info" href="{{ URL::to('blogs/' . $value->id . '/edit') }}">Edit</a> <button type="submit" class="btn btn-xs btn-danger">Delete</button> </form> </td> </tr> @endforeach </tbody> </table> </div> </div> </body> </html> |
Description | URL | Controller Function | View File |
Show the form to create a blogs. | GET example.com/blogs/create | create() | resources/views/blogs/create.blade.php |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php ... /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // load the create form (resources\views\blogs) return View('blogs.create'); } ... |
1 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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}" /> <meta name="description" content=""> <meta name="author" content=""> <title> {{ config('app.name', 'Laravel') }}</title> <!-- Bootstrap Core CSS --> <link href="{{ asset('/assets/vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet"> </head> <body> <div class="container"> <div class="row page-header"> <div class="col-xs-12 col-md-6 col-lg-6"> <h1>Create Blog</h1> </div> <div class="col-xs-12 col-md-6 col-lg-6"> <div class="btn-group pull-right" role="group" aria-label="..." > <a href="{{ URL('/blogs') }}" class="btn btn-default "> Back</a> </div> </div> </div> <!-- /.row --> <div class="row"> <div class="col-md-8"> <form class="form-horizontal" method="POST" action="{{ URL('/blogs') }}"> <!-- if there are creation errors, they will show here --> @if($errors->all()) <ul class="has-error"> @foreach ($errors->all() as $message) <li>{{ $message }}</li> @endforeach </ul> @endif {{ csrf_field() }} <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}"> <label for="title" class="col-md-4 control-label">Title *</label> <div class="col-md-6"> <input id="title" type="text" class="form-control" name="title" value="{{ old('title') }}" required autofocus> @if ($errors->has('title')) <span class="help-block"> <strong>{{ $errors->first('title') }}</strong> </span> @endif </div> </div> <div class="form-group{{ $errors->has('content') ? ' has-error' : '' }}"> <label for="content" class="col-md-4 control-label">Content *</label> <div class="col-md-6"> <textarea name="content" id="content" class="form-control" ></textarea> @if ($errors->has('content')) <span class="help-block"> <strong>{{ $errors->first('content') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Create </button> </div> </div> </form> </div> </div> </div> </body> </html> |
ฟังค์ชันด้านบนสำหรับแสดงฟอร์มเพื่อกรอกข้อมูล เมื่อทำการคลิก Submit Form ระบบจะไปทำงานต่อที่ method store()
Description | URL | Controller Function | View File |
Process the create form submit and save the blog to the database. | POST example.com/blog | store() | NONE |
1 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 ... /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Validate read more on validation at https://laravel.com/docs/5.4/validation $this->validate($request, [ 'title' => 'required|string|max:150', 'content' => 'required|string', ]); // store $blog = new Blog; $blog->title = $request->input('title'); $blog->content = $request->input('content'); $blog->save(); // redirect return redirect('blogs')->with('message', 'Successfully created blog!'); } ... |
Description | URL | Controller Function | View File |
Show one of the nerds. | GET example.com/nerds/{id} | show() | app/views/nerds/show.blade.php |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php ... /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // get the blog $blog = Blog::findOrFail($id); // show the view and pass the blog to it return View('blogs.show') ->with('blog', $blog); } ... |
1 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 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}" /> <meta name="description" content=""> <meta name="author" content=""> <title> {{ config('app.name', 'Laravel') }}</title> <!-- Bootstrap Core CSS --> <link href="{{ asset('/assets/vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet"> </head> <body> <div class="container"> <div class="row page-header"> <div class="col-xs-12 col-md-8 col-lg-8"> <h1>Show Record : {{ $blog->title }}</h1> </div> <div class="col-xs-12 col-md-4 col-lg-4"> <div class="btn-group pull-right" role="group" aria-label="..." > <a href="{{ url()->previous() }}" class="btn btn-default "> Back</a> </div> </div> </div> <!-- /.row --> <div class="row"> <label class="col-sm-2">Title</label> <div class="col-sm-10">{{ $blog->title }}</div> </div> <div class="row"> <label class="col-sm-2">Content</label> <div class="col-sm-10">{{ $blog->content }}</div> </div> <!-- /.row --> </div> </body> </html> |
Description | URL | Controller Function | View File |
Pull blog from the database and allow editing. | GET example.com/blogs/{id}/edit | edit() | resources/views/blogs/edit.blade.php |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php ... /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // get the blog $blog = Blog::findOrFail($id); // show the edit form and pass the blog return View('blogs.edit') ->with('blog', $blog); } ... |
1 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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}" /> <meta name="description" content=""> <meta name="author" content=""> <title> {{ config('app.name', 'Laravel') }}</title> <!-- Bootstrap Core CSS --> <link href="{{ asset('/assets/vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet"> </head> <body> <div class="container"> <div class="row page-header"> <div class="col-xs-12 col-md-6 col-lg-6"> <h1>Edit Blog : {{ $blog->title }}</h1> </div> <div class="col-xs-12 col-md-6 col-lg-6"> <div class="btn-group pull-right" role="group" aria-label="..." > <a href="{{ URL('/blogs') }}" class="btn btn-default "> Back</a> </div> </div> </div> <!-- /.row --> <div class="row"> <div class="col-md-8"> <form class="form-horizontal" method="POST" action="{{ route('blogs.update', $blog->id) }}"> <!-- if there are creation errors, they will show here --> @if($errors->all()) <ul class="has-error"> @foreach ($errors->all() as $message) <li>{{ $message }}</li> @endforeach </ul> @endif {{ csrf_field() }} {{ method_field('PUT') }} <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}"> <label for="title" class="col-md-4 control-label">Title *</label> <div class="col-md-6"> <input id="title" type="text" class="form-control" name="title" value="{{ $blog->title }}" required autofocus> @if ($errors->has('title')) <span class="help-block"> <strong>{{ $errors->first('title') }}</strong> </span> @endif </div> </div> <div class="form-group{{ $errors->has('content') ? ' has-error' : '' }}"> <label for="content" class="col-md-4 control-label">Content *</label> <div class="col-md-6"> <textarea name="content" id="content" class="form-control" >{{ $blog->content }}</textarea> @if ($errors->has('content')) <span class="help-block"> <strong>{{ $errors->first('content') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Update </button> </div> </div> </form> </div> </div> </div> </body> </html> |
หลังจากกดปุ่มอัพเดทแล้วระบบจะไปทำงานต่อที่ method update()
Description | URL | Controller Function | View File |
Process the create form submit and save the nerd to the database. | PUT example.com/blogs | update() | NONE |
1 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 |
<?php ... /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // Validate read more on validation at https://laravel.com/docs/5.4/validation $this->validate($request, [ 'title' => 'required|string|max:150', 'content' => 'required|string', ]); // store $blog = Blog::findOrFail($id); $blog->title = $request->input('title'); $blog->content = $request->input('content'); $blog->save(); // redirect return redirect('blogs')->with('message', 'Successfully updated blog!'); } ... |
Description | URL | Controller Function | View File |
Process the create form submit and save the blog to the database. | DELETE example.com/blogs/{id} | destroy() | NONE |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php ... /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // delete $blog = Blog::findOrFail($id); $blog->delete(); // redirect return redirect('blogs')->with('message', 'Successfully deleted the blog!'); } ... |
ในไฟล์
ให้แทรกปุ่ม Delete ตามโค๊ดด้านล่าง
1 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 |
... @foreach($blogs as $key => $value) <tr> <td>{{ $value->title }}</td> <td>{{ $value->content }}</td> <td>{{ $value->created_at }}</td> <!-- we will also add show, edit, and delete buttons --> <td> <!-- delete the nerd (uses the destroy method DESTROY /blogs/{id} --> <!-- we will add this later since its a little more complicated than the other two buttons --> <form class="form-horizontal" method="POST" action="{{ URL('blogs/'.$value->id) }}"> {{ csrf_field() }} {{ method_field('DELETE') }} <!-- show the nerd (uses the show method found at GET /users/{id} --> <a class="btn btn-xs btn-success" href="{{ URL::to('blogs/' . $value->id) }}">Show</a> <!-- edit this nerd (uses the edit method found at GET /users/{id}/edit --> <a class="btn btn-xs btn-info" href="{{ URL::to('blogs/' . $value->id . '/edit') }}">Edit</a> <button type="submit" class="btn btn-xs btn-danger">Delete</button> </form> </td> </tr> @endforeach ... |
อ้างอิง
https://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers
https://laravel.com/docs/5.4/controllers#resource-controllers
ป้ายกำกับ:laravel