Upload
christen-christensen
View
798
Download
3
Embed Size (px)
Citation preview
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
Google TrendsComparing: Laravel, YII ,Zend
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.)
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
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
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
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
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
Laravel Project - File structure
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
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
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;
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
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) { //});
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”
Create a ToDo Application– Design --
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>
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
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”
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');});
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/
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;
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"> )
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
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
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➲ ]);➲ });
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> </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
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
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>
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>
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
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
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.
Documentation
➲ https://github.com/laravel/laravel➲
➲ https://laravel.com/docs/5.4/installation➲
➲ https://laravel-news.com/➲
➲ https://laracasts.com/➲
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();
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);
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');
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
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,➲ );
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>
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!';➲ });
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;
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.
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
(Clean up)
➲ -Delete Common Database!● Delete tasks and workerbees
➲ Update the Vagrant Config file with Code folder● C:\Users\Christen\.homestead