Professional Documents
Culture Documents
delegates to
Router
match? match? match?
/ /posts /post/{id}
Why is the
Rely on cookies & sessions Need rate limiting
separation for
web.php No prefix applied automatically on "api/" is applied as prefix on endpoints
API.php exists
at all? Web routes are stateful API routes are stateless
Route::GET'/', function() {
return view('welcome');
});
Managing & Naming
Routes
Route::GET'/', function() {
return view('welcome');
})->name('home.index');
Route Parameters
Route::GET'/posts/1', function() {
return 'Blog post 1';
});
Route::GET'/posts/2', function() {
return 'Blog post 2';
});
Route::GET'/posts/{id}', function($id) {
return 'Blog post' . $id;
});
Understanding Templating,
Views and Blade
Request uses
Model
gets routed to
Controller
produces
View
uses
Request
resources/views
home.blade.php
index.blade.php
Route::GET'/', function() {
return view('home.index');
})->name('home.index');
Template Inheritance &
Layouts
resources/views/layouts
app.blade.php directive
argument
name
<head>
<title> Laravel App -@yield('title')</title>
</head>
<body>
<div>
@yield('title')
</div>
</body>
resources/views/layouts
layout.app
@extends('layouts.app')
@section('content')
<h1>Hello World!</h1>
@endsection
Passing and Rendering Data in
Templates
web.php
Route::GET'/posts/{id}', function($id) {
$posts = [
1 => [
'title' => 'Intro to Laravel',
'content' => 'This is a short intro to Laravel'
],
2 => [
'title' => 'Intro to PHP',
'content' => 'This is a short intro to PHP'
]
];
abort_if(!isset($posts[$id]), 404);
return view ('post.show', ['post => $posts['id]]);
});
resources/views/layouts/layout.app
@extends('layouts.app')
@section('title', $post['title'])
@section('content')
<h1> {{$post['title'] }} </h1>
<p> {{ $post['content'] }} </p>
@endsection
Simple View Rendering
Routes
Route::GET'/', function() {
return view('home.index');
})->name('home.index');
Route::view('/','home.index');
Conditional Rendering
@extends('layouts.app')
@section('title', $post['title'])
@section('content')
@forelse($posts as $key => $post)
<div>{{ $key }}.{{ $post['title']}}</div>
@empty
No Post found!
@endforelse
@endsection
Request and Response
Response, Codes, Headers,
and Cookies
Route::GET'/fun/responses', function() {
return redirect('/home');
});
Route::GET'/fun/back', function() {
redirect to the
return back();
previous page
});
redirect to the
Route::GET'/fun/away', function() {
google home page
return redirect()->away('https://google.com');
});
Returning JSON
Route::GET'/fun/download', function() {
return response()->download(public_path('/laravel.jpg'),'documentation.jpg');
});
shortcut for dump and die, the data will go on screem and
execition will stop
example:
array 2 [
"item" => "10"
"context" => 22"
]
Request Input - An overview of Options
whitelisting
$input = $request->only('username','password');
$input = $request->except(['credit_card']);
blacklisting
$input = $request->except('credit_card');
has method is to determine if a value is present on the filled method to determine if a value is present on the
request. It will return true if the value is present on the request and is not empty:
request:
if ($request->hasAny(['name', 'email'])) {
if ($request->has('name')) { //
// });
}
if ($request->hasAny(['name', 'email'])) {
//
});
Middleware - Running Code
Before & After Request
Controllers
Create controller
app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http:Request;
use App\Http\Controllers\HomeController;
app/Http/Controllers/AboutController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http:Request;
use App\Http\Controllers\AboutController;
Route::get('/single', AboutController::class);
Resource Controllers
CRUD
Create, Read, Update, Delete
reading deleting
creating creating
app/Http/Controllers/PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http:Request;
Route::resource('posts', PostController::class);
web.php
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class)
->only(['index','show']);
Configuration and
Environments Overview
copy the .env.example and create another .env file into the
project:
Configuring the Database
Connection
insert the database name in the .env file for example on the
line 18:
Laravel8
Databases Bird's Eye Overview
Migration Overview
Create Model
php artisan make:model demo -m
Rollback Migration
php artisan migrate:rollback
• this action is to delete the table migration
Available Column Types
The schema builder blueprint offers a variety of methods
that correspond to the different types of columns you can
add to your database tables. Each of the available
methods are listed in the figure below:
Understanding Eloquent
ORM Models
Forms Markup
• Create blade.php file
Create a file name create.blade.php under views/posts
folder, responsible for showing the form in the resource
controller.
@extends('layouts.app')
@section('title', 'Create the post')
@section('content')
<form action="{{ route('posts.store')}}"
method="POST">
<div><input type="text" name="title"</div>
<div><textarea name="submit"
value="Create"></div>
</form>
@endsection
Cross Site Request Forgery
Explained
This is your website with a form for
password changing This action that handles password
change. If the user clicking the link is
authenticated, the password gets
changed.
Get
your-website.com/password
POST
CSRF token protects your
your-website.com/password
website from a malicious
requests
opens email
with link The request is blocked, as it
was not sent by the user!
form auto-submitted
GET malicious
website.com/password
The attacker has taken over the user's
user can click a link that contains form. account
The form is auto-submitted by
JavaScript
Generate CSRF Token, that is a unique token sent with your
forums. It is being added as a hidden form field. The token
is also stored in the session.
@extends('layouts.app')
@section('title', 'Create the post')
@section('content')
@csrf
<form action="{{ route('posts.store')}}"
method="POST">
<div><input type="text" name="title"</div>
<div><textarea name="submit" value="Create"></div>
</form>
@endsection
Storing Submitted Data
Input Validation
Displaying Validation @extends('layouts.app')
@section('title', 'Create the post')
Errors @section('content')
@csrf
<div><input type="text" name="title"></div>
@error('title')
<div>{{$message}}</div>
@enderror
<div textarea name="content" ></div>
@if($errors-any())
<div><ul> @foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach </ul></div>
<form action="{{ route('posts.store')}}" method="POST">
<div><input type="text" name="title"</div>
<div><textarea name="submit" value="Create"></div>
</form>
@endsection
Form Request Classes
php artisan make:request StorePost
app/Http/Requests/StorePost.php
$request->session()->flash('status', 'The
blog post was created!'); app.blade.php
<body>
<div>
@if(session('status')
<div style="background: red;
color:white;">
{{ session('status') }}
</div>
@endif
@yield('content')
</div>
</body>
Old Input Helper
create.blade.php
@extends('layouts.app')
@section('title', 'Create the post')
@section('content')
@csrf
<div><input type="text" name="title"> value="{{ old('title') }}"</div>
@error('title')
<div>{{$message}}</div>
@enderror
<div textarea name="content">{{ old('content') }}</div>
@if($errors-any())
<div><ul> @foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach </ul></div>
<form action="{{ route('posts.store')}}" method="POST">
<div><input type="text" name="title"</div>
<div><textarea name="submit" value="Create"></div>
</form>
@endsection
3 ways to perform the assignment when
constructing a new model:
• create static methods
Model Mass public function store(StorePost $request)
Assignment {
BlogPost::create();
}
• create a new model instance, fill all of the properties with the
input & try to save all the data in the database
2. make static methods
public function store(StorePost $request)
{
$post2 = BlogPost::make();
$post2->save();
}
• create the model, fill the properties, but it would not try to save
the model to the database
3. fill method
• use for model that have been created earlier. This method will
accept array as the parameter.
CRUD - Editing,
Updating, and
Deleting
Edit Form
PostsController.php
form.blade.php
node -v
if)mix.inProduction()){
mix.version(); app.blade.php
}
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
<small id="emailHelp" class="form-text text-muted">
We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Styling Single Post Page example:
@extends('layouts,app')
@section('title', $post->title)
@section('content')
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
<p>Added {{ $post->created_at->diffForHumans() }}</p>
@if(now()->diffInMinutes($post->created_at) < 5)
<div class="alert alert-info">New!</div>
@endif
@endsection
Styling Flash Messages & Error
Messages example:
to retrieve all blog posts that don't have any comments ,it may
pass the name of the relationship to the doesntHave and
orDoesntHave methods:
Model Factories
Add a little bit of body text
Model Factory is the way to define data that is predictable and
easy to replicate so that your tests are consistent and controlled.
Model Factory -After Creating,
AfterMaking
Authentication
How Authentication
works in Laravel
Application
Routing
php artisan make:auth
Seeding allows you to consistently re-create the same data in your database and can
be used to: Populate your database with data that is required for your application to
start -
Model Factories
provide a way to define data that is predictableand
easy to replicate so the tests are consistent and controlled.
Model factory inside database
Individual Seeder Class
Deleting Models using event
Deleting Related Model using Cascading
Soft Deletes Query
to have a deleted_at column that should be set to
default null , as it should be of timestamp data type
in the model
Restore deleted Model
Testing Soft Deleted Model
Authorization
There are two primary ways of authorizing
actions: gates and policies. Think of gates and
policies like routes and controllers
Use User model offers two useful methods for authorization “can” and “cant” Define the permission, ex. "manage_users"
Use User model offers two useful methods for authorization “can” and “cant” Check the permission on the front-end, ex. show/hide the button
cant is used to determine the inability to execute the action. Check the permission on the back-
end, ex. can/can't update the data
Query Scope
The scope is just a method that can use in model to
encapsulate the syntax used to execute a query
Local Query Scope
Local scope it only for single model. But can define global
scope then can use with all model
Blade Component
Global Query Scope
the reusable function to apply to a query builder instance to
modify the query
a subset of blade template that allow you to create new custom,
reusable, encapsulated PHP and HTML.
The add method will only add the item to the cache if it dos not already
exist in the cache store. The method will return true if the item is actually
added to the cache.
Storing Items Forever
remove items
from the cache
using the forget
method
Laravel caching backends
Memcached
Database
Redis
File
Array
Cache Facade
Storage Facade
FTP SFTP S3
Drivers
Rockspace Local
One to One Polymorphic Eloquent Relation
For this reason, Laravel allows you to return any mailable directly from a route
closure or controller.
Controller
User
CommentPosted NotifyBlogPostAuthor
NotifyOtherCommentors