50
Introduction to Laravel 5 A PHP Framework Love beautiful code? We do too What is the “the best” PHP Framework? If we’re talking about “most popular in US” then it should be Laravel. If it’s “most popular in ex-USSR and asia” then it’s Yii. If we’re talking about enterprise level support, that’s Symfony without any doubt. If it’s about features and performance, Yii has more out of the box

Presentation laravel 5 4

Embed Size (px)

Citation preview

Page 1: Presentation laravel 5 4

Introduction to Laravel 5 A PHP Framework

Love beautiful code? We do too

What is the “the best” PHP Framework?

If we’re talking about “most popular in US” then it should be Laravel. If it’s “most popular in ex-USSR and asia” then it’s Yii. If we’re talking about enterprise level support, that’s Symfony without any doubt. If it’s about features and performance, Yii has more out of the box

Page 2: Presentation laravel 5 4

Google TrendsComparing: Laravel, YII ,Zend

Page 3: Presentation laravel 5 4

Laravel Homestead pre-packaged Vagrant box

➲ Runs on Windows, Mac or Linux

➲ Includes Nginx, PHP, Database, Node, …+

➲ Uses Vagrant and VirtualBox

➲ See link for more infohttps://laravel.com/docs/5.4/homestead

(You can alternatively use MAMP,WAMP etc.)

Page 4: Presentation laravel 5 4

Homestead Included Software

➲ Ubuntu 16.04➲ Git➲ PHP 7.1➲ Nginx➲ MySQL➲ MariaDB➲ Sqlite3➲ Postgres➲ Composer➲ Node (With Yarn, PM2, Bower, Grunt, and Gulp)➲ Redis➲ Memcached➲ Beanstalkd

Page 5: Presentation laravel 5 4

Steps for installing Environment

➲ (15 min) Install VirtualBox from web(Prefered)

➲ (15 min) Install Vagrant from web

➲ (15 min) Install Homestead by running command● vagrant box add laravel/homestead

➲ Open Git Shell and run: (20 min)● Cd ~● git clone https://github.com/laravel/homestead.git Homestead

Page 6: Presentation laravel 5 4

Steps for installing Environment➲ Go to the new ~\homestead folder and Run

bash init.sh (first time)

➲ Make sure that ”Vagrant up” can run

➲ Go to .homestead➲ Edit homestead.yaml and verify

Virtual Machine, shared folder,Sites (Nginx)➲ To update Nginx on virtual Machine Run

vagrant reload –-provision

➲ Make sure that shared folder exists (C:\Users\Christen\Code)

➲ Edit Host file :● goto C:\Windows\System32\drivers\etc\hosts● Add 192.168.10.10 homestead.app

Page 7: Presentation laravel 5 4

Create the first Laravel project

➲ Server is now ready but there is no laravel project➲

➲ In (git terminal) to access virtual macine, Run➲ ”vagrant ssh”➲

➲ Go to the ”Code” folder➲

➲ (5 min) Use composer to create a project, Run :● composer create-project laravel/laravel Laravel3 5.4 –-prefer-dist

Page 8: Presentation laravel 5 4

Laravel 5.4 Project

➲ Now we have a project , Nice :D➲ We will soon learn more about how laravel works,

great :D

➲ But be aware that, many things can change from one version to the next:File locations, Build scripts, frameworks included and depricated classes.

➲ If you use this guide, then use Laravel ver. 5.4

Page 9: Presentation laravel 5 4

Run App

➲ http://homestead.app/➲

Page 10: Presentation laravel 5 4

Laravel Project - File structure

Page 11: Presentation laravel 5 4

Artisan Command Line Interface

Get the job done by :➲ Using build in commands➲ Or create custom commands.

This tutorial will use some of these,Commen Commands:

● php artisan list● php artisan help migrate● php artisan make:migration create_tasks_table --create=tasks● php artisan migrate● php artisan migrate:rollback● php artisan migrate:refresh● php artisan migrate:refresh –seed● php artisan db:seed● php artisan make:model test2 --migration● php artisan make:model Task

Page 12: Presentation laravel 5 4

Create a Todo App Tutorial➲ We will cover this guide

https://laravel.com/docs/5.1/quickstart#adding-tasks

➲ And cover how to use laravel components:● Commands● Migrations● Models● Build Database Model● Routes● Views● SubViews● Validation● Redirects● CRUD database operations● Styling with Bootstrap● Package managers and compiling css from sass

Page 13: Presentation laravel 5 4

Create a ToDo ApplicationMigrations and Database (mysql)

➲ Create a task model● php artisan make:migration create_tasks_table --create=tasks

➲ Migration - Add a string to the table● $table->string('name');

➲ Update DB from Vagrant-machine Laravel Project● php artisan migrate

➲ Inspect Database● mysql -u homestead -p secret● SHOW DATABASES;● USE homestead;● SHOW TABLES;● DESCRIBE tasks● SELECT * FROM tasks;● Drop table tasks;

Page 14: Presentation laravel 5 4

Create a ToDo Application Eloquent Models

➲ Create a model to go with the table● php artisan make:model Task

➲ See the class that the command created● Go to app folder open Task.php

➲ Naming Convention● Note that the table is called ”tasks” but the class is called ”Task”● Laravel is easier when you stick to the correct conventions.

➲ Create a Model with migration (table)● php artisan make:model Workerbee –-migration● (update migration file with rows etc.)● php artisan migrate

https://laravel.com/docs/5.1/eloquent

Page 15: Presentation laravel 5 4

Create a ToDo Application Routes

➲ Define Routes that Points to controllers or functions➲

➲ Defined in folder ”routes” by web.php or one of the other *.php files.

➲ We will create 3 routes in web.php: ● List, create and delete a TASK

➲ New routes//Add A New TaskRoute::post('/task', function (Request $request) { //});

//Delete An Existing TaskRoute::delete('/task/{id}', function ($id) { //});

Page 16: Presentation laravel 5 4

Create a ToDo Application– Views --

➲ Views are stored in ”resources/views”

➲ A view is returned from a controller● return view('tasks');

➲ View Files are called ”xxxxx.blade.php”

Page 17: Presentation laravel 5 4

Create a ToDo Application– Design --

Page 18: Presentation laravel 5 4

Create a base view

➲ Create resources/views/layouts/app.blade.php➲➲

➲ <!DOCTYPE html>➲ <html lang="en">➲ <head>➲ <title>Laravel Quickstart - Basic</title>➲

➲ <!-- CSS And JavaScript -->➲ </head>➲

➲ <body>➲ <div class="container">➲ <nav class="navbar navbar-default">➲ <!-- Navbar Contents -->➲ </nav>➲ </div>➲

➲ @yield('content')➲ </body>➲ </html>

Page 19: Presentation laravel 5 4

Create the task view

➲ Create resources/views/tasks.blade.php➲

➲ @extends('layouts.app')➲

➲ @section('content')➲

➲ <!-- Bootstrap Boilerplate... -->➲

➲ <div class="panel-body">➲ <!-- Display Validation Errors -->➲

➲ <!-- New Task Form -->➲ <form action="/task" method="POST" class="form-horizontal">➲ {{ csrf_field() }}➲

➲ <!-- Task Name -->➲ <div class="form-group">➲ <label for="task" class="col-sm-3 control-label">Task</label>➲

➲ <div class="col-sm-6">➲ <input type="text" name="name" id="task-name" class="form-control">➲ </div>➲ </div>➲

➲ <!-- Add Task Button -->➲ <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> Add Task➲ </button>➲ </div>➲ </div>➲ </form>➲ </div>➲

➲ <!-- TODO: Current Tasks -->➲ @endsection

Page 20: Presentation laravel 5 4

Notes on View code

➲ app.blade.php ● @yield('content')

➲ tasks.blade.php● @extends('layouts.app')● @section('content')● @endsection

➲ Note that a view is in general only refered to by the first part so ”tasks.blade.php” is ”tasks”

➲ If view is in a folder its refered as ”folder.view”so ”layouts.app”

Page 21: Presentation laravel 5 4

Return tasks view from main route

➲ Go to web.php

➲ Change the default route (/) so it returns the ”tasks” view.

Route::get('/', function () { return view('tasks');});

Page 22: Presentation laravel 5 4

Last Session and beyond

➲ I Gave you an introduction to Laravel 5.4➲ And we started creating a Todo Web App

➲ Today we will:● Route for ”new task”● Validation for ”new task” request● Add task list data to the task view● Include dependencies● Generate SCSS an JS files and include in web app● Add delete button in view● Add Delete Route

➲ But first, lets see the app from last time➲ http://homestead.app/

Page 23: Presentation laravel 5 4

Add logic and validation for ”new task” request

➲ $validator = Validator::make($request->all(), [➲ 'name' => 'required|max:255',➲ ]);➲

➲ if ($validator->fails()) {➲ return redirect('/')➲ ->withInput()➲ ->withErrors($validator);➲ }➲

➲ // Create The Task...

The ->withErrors($validator) call flashes the errors from a validator instance into the session. so errors can be accessed via the $errors variable in views.

➲ Go to web.php➲

➲ use Illuminate\Http\Request;➲ use App\Task;

Page 24: Presentation laravel 5 4

Include a Error Subview

➲ Go to tasks.blade.php and add

● <!-- Display Validation Errors -->● @include('common.errors')

(should be right after the <div class="panel-body"> )

Page 25: Presentation laravel 5 4

Create the error subview

➲ Create resources/views/common/errors.blade.php➲

➲ @if (count($errors) > 0)➲ <!-- Form Error List -->➲ <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

Page 26: Presentation laravel 5 4

add logic in ”new task” route

➲ $task = new Task;➲ $task->name = $request->name;➲ $task->save();➲

➲ return redirect('/');

➲ Go to web.php and add after validation code

Page 27: Presentation laravel 5 4

Run App Test new task

➲ http://homestead.app/

Page 28: Presentation laravel 5 4

Update logic for ”Show Tasks”with Eloquent models and database connection

➲ Update default route at web.php

//Default➲ Route::get('/', function () {➲ $tasks = App\Task::orderBy('created_at', 'asc')->get();➲

➲ return view('tasks', [➲ 'tasks' => $tasks➲ ]);➲ });

Page 29: Presentation laravel 5 4

Add view code to list tasks

➲ Go to tasks.blade.php and add snippet➲ Note syntax @foreach to loop over Tasks ➲

➲ <!-- Current Tasks -->➲ @if (count($tasks) > 0)➲ <div class="panel panel-default">➲ <div class="panel-heading">➲ Current Tasks➲ </div>➲

➲ <div class="panel-body">➲ <table class="table table-striped task-table">➲

➲ <!-- Table Headings -->➲ <thead>➲ <th>Task</th>➲ <th>&nbsp;</th>➲ </thead>➲

➲ <!-- Table Body -->➲ <tbody>➲ @foreach ($tasks as $task)➲ <tr>➲ <!-- Task Name -->➲ <td class="table-text">➲ <div>{{ $task->name }}</div>➲ </td>➲

➲ <td>➲ <!-- TODO: Delete Button -->➲ </td>➲ </tr>➲ @endforeach➲ </tbody>➲ </table>➲ </div>➲ </div>➲ @endif

Page 30: Presentation laravel 5 4

Run App

➲ http://homestead.app/➲

Page 31: Presentation laravel 5 4

Make Bootstrap workInclude dependencies

➲ In Project Folder Run● composer update● Composer show -i

➲ Which installs the dependencies in composer.jsonAnd updates the composer.lock

➲ From host system (with windows), Run:● npm install –no-bin-links

➲ Which installs the definition in package.json

➲ Verify that the packages are now installed● Npm list –depth=1

Page 32: Presentation laravel 5 4

Generate and load Assets

➲ Generate assets by running job ( no minify)● npm run dev

➲ Its desribed in webpack.mix.js file➲ You can (SaSS,LESS, paths, files, combine

extract)➲ See https://laravel.com/docs/5.4/mix for details

➲ Go to layouts/app.blade.php in base view➲ Find header section and include

● <!-- CSS And JavaScript -->● <link href="{{ asset('css/app.css') }}" rel="stylesheet"

type="text/css" >● <script type="text/javascript"

src="{{ asset('js/custom.js') }}"></script>

Page 33: Presentation laravel 5 4

Run App

➲ http://homestead.app/➲

Page 34: Presentation laravel 5 4

Add a delete Button in view➲ Go to tasks.blade.php➲ add button to each row of our task list

➲ <!-- Delete Button -->➲ <td>➲ <form action="/task/{{ $task->id }}" method="POST">➲ {{ csrf_field() }}➲ {{ method_field('DELETE') }}➲

➲ <button>Delete Task</button>➲ </form>➲ </td>

Add to start of header in app.blade.php➲➲ <script>➲ window.Laravel = <?php echo json_encode([➲ 'csrfToken' => csrf_token(),➲ ]); ?>➲ </script>

Page 35: Presentation laravel 5 4

Implement the Delete Request in Route

➲ Route::delete('/task/{id}', function ($id) {➲ Task::findOrFail($id)->delete();➲

➲ return redirect('/');➲ });

➲ Go to routes \ web.php➲ And update the logic in the delete function

Page 36: Presentation laravel 5 4

Run App

➲ http://homestead.app/➲

Page 37: Presentation laravel 5 4

Cool Laravel Features

➲ Its a Framework➲ Good Documentation➲ Laravel eloquent (Models)➲ Routing➲ Send Email➲ Easy Authentication➲ Security➲ Nice packages: Laravel Socialite➲ Enterprise level solutions for:

Payment, login, automation, Localization, Testing

Page 38: Presentation laravel 5 4

Framework

➲ Please dont write your own code from scratch.

➲ If you like php, then Laravel it properly a good choice

➲ It structures your code in a nice way with a Model View Controller approach.

Page 39: Presentation laravel 5 4

Documentation

➲ https://github.com/laravel/laravel➲

➲ https://laravel.com/docs/5.4/installation➲

➲ https://laravel-news.com/➲

➲ https://laracasts.com/➲

Page 40: Presentation laravel 5 4

Laravel eloquent

➲ $tasks = Task::all();➲ ➲ $task = Task::find(1);➲ ➲ $task = Task::find(1);➲ $task->title = 'Put that cookie down!';➲ $task->save();➲ ➲ Task::create([➲ 'title' => 'Write article'➲ ]);➲ ➲ Task::find(1)->delete();

Page 41: Presentation laravel 5 4

Laravel eloquent - relationships

➲ $tasks = User::find(1)->tasks;

➲ $author = Task::find(5)->user()->username;

➲ // Insert a new task by author➲ $task = new Task([ title: 'Go to store.' ]);➲ User::find(1)->tasks()->insert($task);

Page 42: Presentation laravel 5 4

Routing 1Basics

➲ Basic Closure➲ Route::get('users/{id}', function($id) {➲ $user = User::find($id);➲ return View::make('users.profile')➲ ->with('user', $user);➲ });

Refer to Controller➲ Route::get('users/{id}', 'Users@show');

Page 43: Presentation laravel 5 4

Routing 2Resourceful Controllers

➲ Route::resource('tasks', 'TasksController');

➲ GET tasks (Show all tasks)➲ GET tasks/{id} (Show single task)➲ GET tasks/create (create task form )➲ POST tasks (Create a new task)➲ GET task/{id}/edit (Edit single task)➲ PUT tasks/{id} (Update task)➲ DELETE tasks/{id} (Delete task)

➲ php artisan controller:make TasksController➲

➲ Php artisan route:list

Page 44: Presentation laravel 5 4

Emails 1 – setupapp/config/mail.php

➲ <?php➲

➲ ➲ return array(➲ 'host' => 'smtp.example.com',➲ 'port' => 2525,➲ 'from' => array('address' => null, 'name' => null),➲ 'encryption' => 'tls',➲ 'username' => null,➲ 'password' => null,➲ );

Page 45: Presentation laravel 5 4

Emails 2 – templateapp/views/emails/xxxx.blade.php

➲ <?php➲ ➲ <html>➲ <body>➲ Hi there, {{ $user->name }}. Thanks again for

signing up for the latest Justin Bieber news! We'll look forward to seeing you around.

➲ ➲ Thanks,➲ Management➲ </body>➲ </html>

Page 46: Presentation laravel 5 4

Emails 3 – routeapp/routes/web.php

➲ Route::get('/', function()➲ {➲ $user = User::find(1);➲ $data = [ 'user' => $user ];➲ ➲ Mail::send('emails/xxxxxx', $data,

function($message) use($user)➲ {➲ $message➲ ->to($user->email)➲ ->subject('Welcome Bieber Fan!')➲ ->attach('images/bieberPhoto.jpg');➲ });➲ return 'Welcome email sent!';➲ });

Page 47: Presentation laravel 5 4

Easy Authentication

➲ 1: Create a user table with migration command

➲ 2: Route::post('login', function() {➲ $credentials = array(➲ 'username' => Input::get('username'),➲ 'password' => Input::get('password') );➲ if ( Auth::attempt($credentials) ) {➲ // Credentials match. Logged in!➲ return Redirect::to('admin/profile');➲ }➲ });

➲ Refer user:➲ $user = Auth::user()->username;

Page 48: Presentation laravel 5 4

Security➲ Laravel uses hashed and salted passwords➲

➲ Laravel uses prepared SQL statements➲

➲ Laravel provides a convenient way to ➲ escape/unescape user input

➲ Laravel community has been very responsive to bug reports related to security

➲ Validate Input from Requests.

Page 49: Presentation laravel 5 4

Laravel Socialite(Social Login)

➲ Laravel Socialite provides an expressive, fluent interface to OAuth authentication with Facebook, Twitter, Google, LinkedIn, GitHub and Bitbucket.

➲ See webpage for all the Laravel features:https://laravel.com/docs/5.4

Page 50: Presentation laravel 5 4

(Clean up)

➲ -Delete Common Database!● Delete tasks and workerbees

➲ Update the Vagrant Config file with Code folder● C:\Users\Christen\.homestead