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

Post on 05-Aug-2020

10 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Wichan ThumthongPatikom Thongjing

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

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

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/

Setup and Install

Install Laravel

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

Open ProjectCLI Mode

Views> Integrated Terminal

Run Project php artisan serve

.ENV (Environmental Variables)

Database configurations

Application configurationslocal/production

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

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

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

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

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

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

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

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.

- 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

URL = File locationIs a bad idea.

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.

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

Laravel Diagram

Routing

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

Routing Parameters

New, Return and Grouping Views

Files name

- about.blade.php

Return Views

- return view(‘about’);

Return Grouping Views

- return view(‘public.about’);

Passing data to viewsFiles name

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

Views

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

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 --}}

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> !!}

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>

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

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

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

- php artisan make:controller PhotosController --resource

Routing Controller

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

Resource Controllers

Layout (Blade template engine)

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>

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 และ อนๆ- เพอเรยกใชงานใหถกตอง และลดระยะเวลาในการพฒนา

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);}

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

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

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

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

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

- php artisan make:migration create_categories_table- php artisan migrate

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

- php artisan make:migration create_products_table- php artisan migrate

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

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

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

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' => 'โปรแกรมคอมพวเตอร' ]); }

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

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

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(); }

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’);

Resource Controller, RESTful Controller

Resource Controller, RESTful Controller

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

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);

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

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

]); }

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();

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() }}

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’];

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

Return Back

- return back();

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();

Model Accessors/GetterNew Attributes

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

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

}- {{ $list->fullname }}

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”;}

Relations

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();

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’);

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’);

}

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;

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]);

Web Forms

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

Web FormsOpen A Form

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

Example ProjectsUsers Management

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

Create New Database

Database Config

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

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

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(); }); }

RelationsUser.php

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

New Migratephp artisan migrate

Tinkerphp artisan tinker

Make Controllerphp artisan make:controller --resource AdminUsersController

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

AdminUsersControllerreturn view('users.index');

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); }

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>

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>

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

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(); }

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]); }

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', ]; }

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

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>

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

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

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>

top related