Laravel Module Print
Laravel Module Print
delegates to
Router
/ /posts /post/{id}
Why is the
separation
Rely on cookies
& sessions Need rate limiting
web.php endpoints
endpoints automatically
&
API.php Web routes are
stateful API routes are stateless
exists at
all?
Authentication done via VerifyCsrf
Authentication
done via API token
middleware
HTTP verb names
GET
POST
PUT/PATCH
DELETE
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/named-route', function() { page that have
return redirect()->route('posts.show',['id'=>1]); been set the
}); name
->name('home.index');
Route::GET'/fun/away', function() {
redirect to the
return redirect()->away('https://google.com');
google home
});
page
Returning JSON
Route::GET'/fun/download', function() {
return response()->download(public_path('/laravel.jpg'),'documentation.jpg');
});
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 filled method to determine if a value is
on the request. It will return true if the value is present on the request and is not empty:
present on the 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
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
1. 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 your-
website.com/password
CSRF token protects
your 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
@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 @extends('layouts.app')
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:
1. create static methods
Model Mass public function store(StorePost $request)
Assignment {
BlogPost::create();
}
create the model, fill the properties, but it would not try
to save the model to the database
3. fill method
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:
Have different ways can authorize actions using Policies Gates are Permissions
Use User model offers two useful methods for authorization Check the permission on the front-end, ex. show/hide the
“can” and “cant” button
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
A one-to-one polymorphic relation is similar
to a typical one-to-one relation; however,
the child model can belong to more than
one type of model using a single
association.
Model Structure
One to Many Polymorphic
Eloquent Relation
For this reason, Laravel allows you to return any mailable directly from
a route closure or controller.
Controller
User
Respond Remote
SMTP/ cloud
mail server
Observers
creating the closures and the routes inside your Web
and creating controllers and for the model events.
CommentPosted NotifyBlogPostAuthor
NotifyOtherCommentors
Facades
Laravel facades serve as "static proxies" to underlying classes in the
service container, providing the benefit of a terse, expressive syntax while
maintaining more testability and flexibility than traditional static methods.
Apply middlewares or
RouteServiceProvider middleware() middleware group
Set controller
mapWebRoutes() mapApiRoutes() namespace() namespace