patikom thongjing wichan thumthong · - introduction to laravel - introduction to mvc - controller,...

90
Wichan Thumthong Patikom Thongjing สไลด์ประกอบบการบรรยาย : https://goo.gl/rsXAoW หนังสือประกอบการบรรยาย : 300 ลดเหลือ 250 บาท [มีหรือไม่ก็ได้] ซอฟต์แวร์ติดตั˓ง :

Upload: others

Post on 05-Aug-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Wichan ThumthongPatikom Thongjing

สไลดประกอบบการบรรยาย : https://goo.gl/rsXAoWหนงสอประกอบการบรรยาย : 300 ลดเหลอ 250 บาท [มหรอไมกได] ซอฟตแวรตดตง :

Page 2: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Outline- Setup and Install - Introduction to Laravel- Introduction to MVC- Controller, Layouts, Views and Assets- Artisan, Database Migrations and Seeding- Model, Eloquent ORM and Relationships- Web Form and Form Validation- Authenticating, Users and Sessions

Page 3: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Setup and InstallXAMPP

XAMPP is an easy to install Apache distribution containing MariaDB, PHP and Perl.

https://www.apachefriends.org/index.html

Visual Studio Code

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.

Composer

Dependency Manager for PHP. Latest: v1.6.4. Getting Started Download · Documentation Browse Packages · Issues GitHub

https://getcomposer.org/

Page 4: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a
Page 5: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Setup and Install

Install Laravel

composer create-project --prefer-dist laravel/laravel PorjectName

Page 6: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Open ProjectCLI Mode

Views> Integrated Terminal

Page 7: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Run Project php artisan serve

Page 8: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

.ENV (Environmental Variables)

Database configurations

Application configurationslocal/production

ตอนขน Production ให Cofig คาตาง ๆ โดยใชคาสงphp artisan config:cache

หากมการแกไขไฟล env ยกเลกหรอลาง Cache โดยใชคาสงphp artisan config:clear

Page 9: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Introduction to MVCThe problem with writing web applications with “include or require”

Page 10: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

The ProblemsWeb programming

- Difficult to maintain the code : script file are unstructural.

- Difficult to develop : application logic is mixed up with presentation.

- In secure : database passwords are in a files in a publicly-accessible folder.

Use a frameworkA framework is a library of code. It provides structure that you can use to build your application on.

- You can code faster.- More than one person.- The code is less complicated, so

therefore easier to maintain.- More secure : can be stored “Database

Password” outside of the publicly accessible folder.

The Solutions

Page 11: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

The MVC pattern

What it is? And how it can help you write better code.

Models : are where and application’s data are stored. Responsible for storing and retrieving data. Know nothing about the user interface.

Business Data, Business Logic

Model

Page 12: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

The MVC pattern

What it is? And how it can help you write better code.

Views : are what the user sees on the screen. They present the data to the user. Know nothing about models.

HTML, CSS, JavaScript, PHP

Views

Page 13: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

The MVC pattern

What it is? And how it can help you write better code.

Controller : are what the user interact with. They receive a request from the user, decide what to do, and send a response back. It’s only component that interacts with models.

GET, POST, Request, Call Model, Call Views

Controller

Page 14: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Why use MVC?

Business logic separate from presentation : separation of concerns

- Easier to reuse code.- Developing is faster.- Code is more organised.- Easier to understand. - Easier to maintain.- Easier to test the code.- More secure.

Page 15: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

- Designer can focus on the front end without worrying about the business logic.

- The developers of the models can focus on the business logic or back end without worrying about the look and feel.

Developer Specialisation

Page 16: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

URL = File locationIs a bad idea.

Page 17: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Using a front controller

- The URL does not map to an individual PHP script.- All requests are sent through on page.- This is called a Front Controller

- Provides a central entry point for all request.- Handles everything common to every request such as

session handling etc.

Page 18: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Introduction to LaravelMain Features

- Routings- Configuration management- Query builder and ORM Eloquent - Schema builder, migrations and seeding- Blade template engine- E-mailing- Authentication, Middleware, Socialite- Event, Queues and Redis

Page 19: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a
Page 20: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Laravel Diagram

Page 21: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Routing

Page 22: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Routing Method- get()- post()- put()- patch()- delete()- any()

Page 23: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Routing Parameters

Page 24: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

New, Return and Grouping Views

Files name

- about.blade.php

Return Views

- return view(‘about’);

Return Grouping Views

- return view(‘public.about’);

Page 25: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Passing data to viewsFiles name

- return view('about', ['name' => 'Wichan Thumthong']);

Views

- DATA Name : <b> {{ $name }} </b>- Comment : {{-- COMMENT --}}

Page 26: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Passing multiple data to viewsFiles name

- $name = ‘Wichan’;$surname= ‘Thumthong’;return view('about', compact(‘name’, ‘surname’));

Views

- DATA Name : <b> {{ $name }} {{ $surname}}</b>- Comment : {{-- COMMENT --}}

Page 27: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Passing array to viewsFiles name

- $data = array( $name =>‘Wichan’,$surname=> ‘Thumthong’);

return view('about')->with($data);

Views

- DATA Name : <b> {{ $name }} {{ $surname}}</b>- Comment : {{-- COMMENT --}}- Name : {{ $name or ‘Empty Name’ }}- Script : {!! <script>alert(‘Hello world’)</script> !!}

Page 28: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Looping an array in viewsFiles name

- $data = [‘Education’, ‘Engineering’, ‘Technology’, ‘Sciences’];return view('about')->with(‘data’, $data);

Views

- <ul>@foreach($data as $list)<li>{{ $list }}</li>@endforeach</ul>

Page 29: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

If conditional in viewsViews

- @if ($condition)<p>Data information</p>

@else<p>Data information</p>

@endif

Views

- @if (count($data) >1)<p>Data information</p>

@elseif(count($data)==1)<p>{{ $data[0] }}</p>

@else<p>Empty!!</p>

@endif

Page 30: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

ControllersMake new Home Controllers (app/Http/Controllers)

- php artisan make:controller HomeController

Routing Controller

- Route::get(‘/home’, ‘HomeController@index’);

Method

- public function index(){return ‘Index at Home controller’;

}

ชอ Controller

ชอ Method หรอ Function ทอยใน Controller

Page 31: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Resource ControllersMake new Resource Controllers (app/Http/Controllers)

- php artisan make:controller PhotosController --resource

Routing Controller

- Route::resource(‘/photos’, ‘PhotosController’);

Page 32: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Resource Controllers

Page 33: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Layout (Blade template engine)

Page 34: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Layout (Blade template engine)layout.blade.php

<html><head> @yield(‘css’)</head><body>

@yield(‘content’)</body></html>

page.blade.php

@extends(‘layout’)

@section(‘css’)<link rel=’stylesheet’ ...>

@endsection

@section(‘content’)<h2>ShowContent</h2>

@endsection

Views

<html><head> <link rel=’stylesheet’ …></head><body>

<h2>ShowContent</h2></body></html>

Page 35: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

CSS and JS assetsAssets from public Directory

- <link rel="stylesheet" href="{{ assets('/css/app.css') }}">- <img src= “{{ asset(‘/images/logo.jpg’)}}”>- <a href= “{{ url(‘/login’) }}”></a>

Helper Functions

- https://laravel.com/docs/5.6/helpers - Helper เปนฟงกชนสาหรบอานวยความสะดวกใหกบนกพฒนา ทง Arrays,

Paths, String, Url, asset, dd, bcrypt, redirect และ อนๆ- เพอเรยกใชงานใหถกตอง และลดระยะเวลาในการพฒนา

Page 36: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Authentication- php artisan make:auth- php artisan migrate

- ระบบจะถกสรางขนมาแบบอตโนมตทงการสมครสมาชก การเขาสระบบ การออกจากระบบ และมตวอยางหนา Views

- กอน Migrate ฐานขอมลใหสรางฐานขอมลและกาหนดคาในไฟล ENV ใหเสรจเรยบรอยแสยกอน

- Laravel 5.4 ปรบแกไขไฟล app/providers/AppServiceProvider.php

use Illuminate\Support\Facades\Schema;public function boot(){ Schema::defaultStringLength(191);}

Page 37: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Bootstrap 4 Template ( https://startbootstrap.com/ )

Page 38: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Bootstrap 4 Template ( http://bootswatch.com )

Page 39: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Artisan, Migration และ Seeding- Artisan เปนชดคาสงทเรยกผาน CLI

(Command Line Interface) สาหรบการสราง หรอบรหารจดการโปรเจค

- Database Migration ตวชวยในการจดการโครงสรางของตาราง สาหรบจดเกบขอมลภายในฐานขอมล

- Seeding เปนการกาหนดขอมลเรมตนใหกบตาราง

Artisan

- php artisan --version- php artisan route:list- php artisan down- php artisan up- php artisan route:cache

Page 40: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Artisan, Migration และ SeedingArtisan Generators

- make:command- make:console- make:controller- make:event- make:middleware- make:migration- make:model- make:provider- make:request

Migrations

- php artisan migrate: Keyword

Keywords

- install- refresh- reset- rollback- status

Page 41: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Artisan, Migration และ SeedingMake migration https://laravel.com/docs/5.6/migrations

- php artisan make:migration create_categories_table- php artisan migrate

Page 42: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Artisan, Migration และ SeedingMake migration https://laravel.com/docs/5.6/migrations

- php artisan make:migration create_products_table- php artisan migrate

Page 43: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Artisan, Migration และ SeedingAdding and Removing Column ->after(‘street’)

- php artisan make:migration add_new_column_to_users --table=users- php artisan migrate

Page 44: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Artisan, Migration และ SeedingSeeding https://laravel.com/docs/5.6/seeding

- php artisan make:seeder UsersTableSeeder- php artisan db:seed --class=UsersTableSeeder- php artisan db:seed

Page 45: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Artisan, Migration และ SeedingSeeding https://laravel.com/docs/5.6/seeding

public function run() { DB::table('categories')->insert([ 'name' => 'Smart Phone', 'detail' => 'สมารทโฟน' ]); DB::table('categories')->insert([ 'name' => 'NoteBook', 'detail' => 'โนตบก' ]); DB::table('categories')->insert([ 'name' => 'Computer', 'detail' => 'อปกรณคอมพวเตอร' ]); DB::table('categories')->insert([ 'name' => 'Storage', 'detail' => 'อปกรณจดเกบขอมล' ]); DB::table('categories')->insert([ 'name' => 'Software', 'detail' => 'โปรแกรมคอมพวเตอร' ]); }

Page 46: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

ModelsModels https://laravel.com/docs/5.6/eloquent

- php artisan make:model Product -m-m หมายถง ใหสราง Migration ดวย ถามตารางอยแลวไมตองใส

Page 47: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Artisan, Migration และ SeedingSeeding https://laravel.com/docs/5.6/seeding

- php artisan make --seeder public function run() { $ca1 = new App\Category(); $ca1->name = 'Speaker'; $ca1->detail = 'ลาโพง'; $ca1->save(); }

Page 48: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Resource Controller, RESTful ControllerMake Controller (App/http/Controllers)

- php artisan make:controller ProductsController --resource- php artisan make:controller CategoriesController --resource

Route

- Route::resource(‘/admin/products’, ‘ProductsController’);- Route::resource(‘/admin/categories, ‘CategoriesController’);

Page 49: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Resource Controller, RESTful Controller

Page 50: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Resource Controller, RESTful Controller

Page 51: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Resource Controller, RESTful ControllerApp/http/controllers

public function index() { $cat = Category::all(); return view('categories.index', ['cat'=>$cat]); }

Views/categories/index.blade.php

@extends('layouts.app')

@section('content')<div class="container"> <h3>หมวดหมสนคาทงหมด</h3> <ul> @foreach($cat as $item) <li>{{ $item->name}} ({{ $item->detail }})</li> @endforeach </ul></div>@endsection

Page 52: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Finding Data- $cat = Category::all();- $cat = Category::find(1);- $cat = Category::where(‘name’, ‘=’, ‘computer’)->first();- get();

- $cat = Category::select(‘name’, ‘computer’)->first();- $cat = category::all()->random(2);

Page 53: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Finding Data- $cat = Category::all();- $cat = Category::find(1);- $cat = Category::where(‘name’, ‘=’, ‘computer’)->first();

Page 54: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

SQL Functions- $count = Category::count();- $max = Category::max(‘id’);- $min = Category::min(‘amount’);- $avg = Category::avg(‘amount’);- $sum = Category::sum(‘amount’);

ตวอยางการ Count

public function index() { $cat = Category::all(); $count = Category::count(); return view('categories.index', [

'cat'=>$cat, 'count'=>$count

]); }

Page 55: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Filter- $cat = Category::where(‘id’, ‘=’, ‘w001’)->get();- $cat = Category::where(‘name’, ‘LIKE’, ‘a%’)->get();- $cat = Category::where(‘id’, ‘=’, 1)->get();- $cat = Category::where(‘id’, ‘!=’, 1)->get();- $cat = Category::whereBetween(‘age’, [13, 25])->get();- $cat = Category::whereNotBetween(‘age’, [13, 25])->get();- $cat = Category::whereBetween(‘price’, [1000, 2500])->get();- $cat = Category::where(‘id’, ‘=’, ‘w001’)->get()->where(‘name’, ‘LIKE’,

‘a%’)->get();- $cat = Category::where(‘id’, ‘=’, ‘w001’)->get()->orWhere(‘name’, ‘LIKE’,

‘a%’)->get();

Page 56: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Filter- $cat = Category::whereNull(‘name’)->get();- $cat = Category::whereNotNull(‘name’)->get();

Order By and Limit (Default ASC:นอยไปหามาก)

- $cat = Category::orderBy(‘name’)->get();- $cat = Category::orderBy(‘id’, ‘desc’)->limit(5)->get();

Pagination

- $cat = Category::paginate(20); $cat = Category::simplePaginate(20); - {!! $cat->render() !!}- {{ $cat->total() }}

Page 57: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Saving/Updating Data- $cat -> name = ‘Computer’;

$cat->save();- $data = [‘name’=> ‘Computer’, ‘detail’=> ‘Computer Technology’];

$cat->create($data);- $cat->create([‘name’=> ‘Computer’, ‘detail’=> ‘Cdetail’]);

Fillable Model

- protected $fillable = [‘name’, ‘detail’];

Page 58: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Deleting Data- $cat = Category::find(1);- $cat->delete();- Category::destroy();- Category::destroy(1,2,3,4,5)- Category::truncate();

Return Back

- return back();

Page 59: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Model Query Scope- Class User extends Model {

public function scopeOver($query){$today = Carbon::now()->subYear(21);Return $query->where(‘birth’, ‘<’, $today);

}}

- $user = User::over()->get();

Page 60: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Model Accessors/GetterNew Attributes

- Class User extends Model {public function getFullnameAttribute(){

Return $this->first_name.“ ”.$this->last_name;}

}- {{ $list->fullname }}

Page 61: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Defining MethodsNew Attributes

- Class User extends Model {public function isAdmin(){

if($this->status==1){ return true; }else{ return false;}}

}- $user = User::find(1);

if($user->isAdmin()){echo “Admin”;}else{echo “General User”;}

Page 62: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Relations

Page 63: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Eloquent RelationsOne to One Relation

$table->integer(‘user_id’)->unsigned();$table->foreign(‘user_id’)->references(‘id’)->on(‘users’)->onDelete(‘cascade’);

Defining the Relation

public function profile(){return $this->hasone(‘App\Profile’);

}

Call Relation

$user = User::find(1)->profile->telephone;

One to One Relation

$profile = new Profile;$profile->telephone = ‘0838885883’;$user = User::find(1);$user->profile()->save($profile);

$user = User::find(1);$user->profile()->delete();

Page 64: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Eloquent RelationsOne to One Relation with Belongs To

Defining the Relation

public function user(){return $this->belongsTo(‘App\User’);

}

Call Relation

$email = Profile::where(‘telephone’, ‘0838885883’)->get()->first()->user->email;

Define Foreign Key

return $this->belongsTo(‘User’, ‘user_id’);

Page 65: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Eloquent RelationsOne to Many Relation

Defining the Relation

public function task(){return $this->hasMany(‘App\Task’);

}

Call Relation

$user= User::find(1);$task = new Task;$task->name = ‘New Task’;$task->detail = ‘New Task Detail’;$user->task()->save($task);

public function user(){return $this->belongsTo(‘App\User’);

}

Page 66: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Eloquent RelationsMany to Many Relation

Defining the Relation

public function roles(){return $this->belongToMany(‘App\Role’);

}

public function users(){return $this->belongToMany(‘App\Role’);

}

Call Relation

$roles = User::find(1)->roles;$admins = Role::find(1)->users;

Page 67: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

SQL QueriesUse DB;

$users = DB::select(‘select * from users where active =?’, [1]);

$update = DB::update(‘update users set usertype =?’, [1]);

$deleted = DB::delete(‘delete from user where user_id = ?’, [1]);

Page 68: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Web Forms

Page 69: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Web FormsLaravel Collective https://laravelcollective.com/docs/master/html

- composer require "laravelcollective/html":"^5.4.0"- 'providers' => [

// ... Collective\Html\HtmlServiceProvider::class, // ... ],

- 'aliases' => [ // ... 'Form' => Collective\Html\FormFacade::class, 'Html' => Collective\Html\HtmlFacade::class, // ... ],

- Composer update

Page 70: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Web FormsOpen A Form

https://laravelcollective.com/docs/master/html

Page 71: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Example ProjectsUsers Management

Page 72: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Create New Projectcomposer create-project --prefer-dist laravel/laravel NewProjects

Create New Database

Page 73: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Database Config

Page 74: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Run projectphp artisan serve

Make Authenticationphp artisan make:auth

- Laravel 5.4 ขนไปปรบแกไขไฟล app/providers/AppServiceProvider.php

use Illuminate\Support\Facades\Schema;public function boot(){ Schema::defaultStringLength(191);}

- php artisan config:cache

Migratephp artisan migrate

Page 75: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Create Views

public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->integer('role_id')->index()->unsigned()->nullable(); $table->integer('is_active')->default(0); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); }

User Table Migrate

Page 76: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Make Role ModelPhp artisan make:model Role -m

Config Role Migration

public function up() { Schema::create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); }

Page 77: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

RelationsUser.php

public function role(){ return $this->belongsTo('App\Role'); }

New Migratephp artisan migrate

Tinkerphp artisan tinker

Page 78: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Make Controllerphp artisan make:controller --resource AdminUsersController

Route/web.phpRoute::resource('/admin/users', 'AdminUsersController');

AdminUsersControllerreturn view('users.index');

Page 79: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Sending Users to Viewsuse App\User;

public function index() { $users = User::all(); return view('users.index', ['users' => $users]); }

public function create() { return view('users.create); }

Page 80: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Displaying Users in Views

<div class="container"><h1>จดการผใชงาน</h1><table class="table"><thead> <tr> <th>id</th> <th>name</th> <th>email</th> <th>create</th> <th>update</th> </tr></thead>

<tbody>@if($users) @foreach($users as $user) <tr> <td>{{ $user->id }}</td> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> <td>{{ $user->created_at }}</td> <td>{{ $user->updated_at->diffForHumans() }}</td> </tr> @endforeach@endif</tbody></table></div>

Page 81: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Relation Data

<div class="container"><h1>จดการผใชงาน</h1><table class="table"><thead> <tr> <th>id</th> <th>name</th> <th>email</th> <th>role</th> <th>active</th> <th>create</th> <th>update</th> </tr></thead>

<tbody>@if($users) @foreach($users as $user) <tr> <td>{{ $user->id }}</td> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> <td>{{ $user->role->name }}</td> <td>{{ $user->is_active == 1 ? 'Active' : 'Not Active' }}</td> <td>{{ $user->created_at }}</td> <td>{{ $user->updated_at->diffForHumans() }}</td> </tr> @endforeach@endif</tbody></table></div>

Page 82: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Use Web FormsLaravel Collective https://laravelcollective.com/docs/master/html

- composer require "laravelcollective/html":"^5.4.0"- 'providers' => [

// ... Collective\Html\HtmlServiceProvider::class, // ... ],

- 'aliases' => [ // ... 'Form' => Collective\Html\FormFacade::class, 'Html' => Collective\Html\HtmlFacade::class, // ... ],

- Composer update

Page 83: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

views/admin/users/create.blade.php<div class="container"><h2>เพมขอมลผใช</h2>

{!! Form::open(['method'=>'POST', 'action'=>'AdminUsersController@store']) !!} <div class="form-control"> {!! Form::label('name', 'Name') !!} {!! Form::text('name', null, ['class'=>'form-control']) !!} </div> <div class="form-control"> {!! Form::submit('Create User', ['class'=>'form-control']) !!} </div>{!! Form::close() !!}

</div>

public function store(Request $request) { return $request->all(); }

Page 84: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

views/admin/users/create.blade.phpStatus Select box <div class="form-control"> {!! Form::label('is_active', 'Status:') !!} {!! Form::select('is_active', array(1=>'Active', 0=>'Not Active'), null, ['class'=>'form-control']) !!} </div>

Role ID Select Box

<div class="form-control"> {!! Form::label('role_id', 'Role:') !!} {!! Form::select('role_id', [''=>'Choose Options'] + $roles , null, ['class'=>'form-control']) !!} </div>

Use App\Role; public function create() { $roles = Role::pluck('name', 'id')->all(); return view('users.create', ['roles'=>$roles]); }

Page 85: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

views/admin/users/create.blade.phpPassword <div class="form-control"> {!! Form::label('password', 'Password:') !!} {!! Form::password('password', null, ['class'=>'form-control']) !!} </div>

Create UserCreateRequest

php artisan make:request UserCreateRequest

Config App/http/Requests/UserCreateRequest.php

public function authorize() { return true; }

public function rules() { return [ 'name' => 'required', 'email' => 'required', 'password' => 'required', 'role_id'=> 'required', 'is_active' => 'required', ]; }

Page 86: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

views/admin/users/create.blade.phpAdminUsersController.php

use App\Http\Requests\UserCreateRequest; public function store(UserCreateRequest $request) { return $request->all(); }

@include(‘includes.form_error’)

@if(count($errors)>0) <div class="alert alert-danger"> <ul> @foreach($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif

Page 87: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

views/admin/users/create.blade.phpUploadFiles

{!! Form::open(['method'=>'POST', 'action'=>'AdminUsersController@store', 'files'=>true]) !!} <div class="form-control"> {!! Form::label('photo_id', 'Photo:') !!} {!! Form::file('photo_id', null, ['class'=>'form-control']) !!} </div> {!! Form::close() !!}

</div>

Page 88: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Add Photo id to UsersMake Migration

php artisan make:migration add_photo_id_to_users --table=users

databases/migrations/

public function up() { Schema::table('users', function (Blueprint $table) { $table->string('photo_id')->nullable();; }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('photo_id'); }); }

php artisan migrate

Page 89: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

Mass AssignmentApp/User

protected $fillable = [ 'name', 'email', 'password', 'role_id', 'is_active', 'photo_id' ];

Create Model Photo

php artisan make:model Photo -m

Update Migration Photo

Schema::create('photos', function (Blueprint $table) { $table->increments('id'); $table->string('file'); $table->timestamps(); });

app/Photo.php

protected $fillable = ['file'];

app/User.php

public function photo(){ return $this->belongsTo('App\Photo'); }

php artisan migrate

Page 90: Patikom Thongjing Wichan Thumthong · - Introduction to Laravel - Introduction to MVC - Controller, Layouts, Views and Assets - Artisan, Database Migrations and Seeding ... Use a

views/admin/users/create.blade.phpAdminUsersController.php

public function store(UserCreateRequest $request) { $input = $request->all(); if($file = $request->file('photo_id')){ $name = time().$file->getClientOriginalName(); $file->move('images', $name); $photo = Photo::create(['file'=>$name]); $input['photo_id'] = $photo->id; } $input['password'] = bcrypt($request->password); User::create($input); return redirect('admin/users'); }

App/User.php public function photo(){ return $this->belongsTo('App\Photo'); }

index.blade.php<td>{{ $user->photo ? $user->photo->file : 'no user photo' }}</td>