You are on page 1of 189

Laravel

web application framework with expressive, elegant syntax


Creating New Laravel
Project Using Composer
To create a new project using Composer run:
> composer create-project laravel/laravel laravel

Let's explain this command step by step:


• composer calls the Composer executable
• create-project is the Composer command that creates a new project
• laravel/laravel - PHP project might use a skeleton, in our case that is the Laravel
Framework. The Composer uses the package repository called Packagist -
https://packagist.org/packages/laravel/laravel. Every package added there (which
Laravel Framework is) has its unique name. Laravel framework's unique name is
laravel/laravel
• laravel is the directory in which your project will be created, relative to where
you are in your Terminal application right now.
WHERE do I create the project
That depends.
The following lectures in the next 2 sections describe how to set up an Apache
webserver with a custom domain, laravel.test. If you want that (it's optional), then
you need to create the project in:
/Applications/XAMPP/xamppfiles/htdocs - on Mac
c:\xampp\htdocs - on Windows
To be clear, you need your terminal to be in these directories and run the above
composer command.
If you don't plan to use Apache - it's fine, that is not required. Then, you can create
the project ANYWHERE you wish. Remember, then you'll have to run the
development web server from within the project directory: php artisan serve
Understanding Routing in
Laravel
visits
https://mypage.com/post/1

delegates to

Router
match? match? match?

/ /posts /post/{id}

Controller Controller Controller


Web API

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

& endpoints automatically

API.php exists
at all? Web routes are stateful API routes are stateless

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

if / else unless / endunless • isset() - is variable or array


if ( true === condition){ • Condition has to be false key defined
echo "Content"; • No alternatives • empty() - is false, 0, empty
}{ else { array
echo "Other content"
}
Loops in Templates
'for each' example:

@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() use($posts) {


return response($posts, 201)
->header('Content-Type','application/json')
->cookie('MY_COOKIE','Piotr Jura', 3600);
});
create a new response object • header set the response header like contents
typed
• cookie keep users' specific data on the browser
side

Route::GET'/fun/responses', function() use($posts) {


return response($posts, 201)
->header('Content-Type','application/json')
->cookie('MY_COOKIE','Piotr Jura', 3600);
});
Redirect Responses

Route::GET'/fun/responses', function() {
return redirect('/home');
});
Route::GET'/fun/back', function() {
redirect to the
return back();
previous page
});

redirect to the page


Route::GET'/fun/named-route', function() { that have been set
return redirect()->route('posts.show',['id'=>1]); the name
});
->name('home.index');

redirect to the
Route::GET'/fun/away', function() {
google home page
return redirect()->away('https://google.com');
});
Returning JSON

Route::GET'/fun/json', function() use($posts) {


return response()->json($posts);
});
json example:
{
"item":"Intro to Laravel",
"content":"This is a short intro to Laravel"
}
Returning File Downloads
path to the file

Route::GET'/fun/download', function() {
return response()->download(public_path('/laravel.jpg'),'documentation.jpg');
});

optional name, the user will see it it needs


to be different from the original
Grouping Routes

Routes can be grouped

Grouped routes share attributes:


URL prefix
Name prefix
Middleware
Route::prefix('fun')->name('fun.')->group(function(){
Route::GET'/', function() {
return view('home.index');
})->name('home.index');
});
Request Input
(Reading User Input)
Route::GET'/posts', function() use ($posts){
request()->all();
return view('posts.index'), ['posts' => $posts])
});

Route::GET'/posts', function() use ($posts){


dd(request()->all());
return view('posts.index'), ['posts' => $posts])
});

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

$input = $request->only(['username', 'password']);

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')) { //
// });
}

when given an array, the whenHas method will


determine if all of the specified values are present:
whenfilled method will execute the givem callback if a
value is a present on the request and is not empty:
$request->whenHas('name', function ($input){
//
});
$request->whenfillee('name', function ($input) {
//
});
hasAny method returns true if any of the specified values
are present:

if ($request->hasAny(['name', 'email'])) {
//
});
Middleware - Running Code
Before & After Request
Controllers
Create controller

php artisan make:controller HomeController

app/Http/Controllers/HomeController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http:Request;

class HomeController extends Controller


{
public function home()
{
return view('home.index');
}
}
web.php

use App\Http\Controllers\HomeController;

Route::get('/', [HomeController::class, 'home'])


->name('home.index');
Single Action Controllers
Create controller

php artisan make:controller AboutController

app/Http/Controllers/AboutController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http:Request;

class AboutController extends controller


{
public function _invoke()
{
return 'Single';
}
}
web.php

use App\Http\Controllers\AboutController;

Route::get('/single', AboutController::class);
Resource Controllers
CRUD
Create, Read, Update, Delete

reading deleting

HTTP GET HTTP DELETE Verb


Route
Route::get() method Route::delete() method

creating creating

HTTP POST HTTP PUT


Route::post() method Route::put() method
Implementing a Resource
Controller
Create controller
php artisan make:controller PostController --resource

app/Http/Controllers/PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http:Request;

class AboutController extends controller


{
public function index()
{ // }
public function create()
{ // }
public function store(Request $request)
{ // }
public function show($id)
{ // }
public function edit($id)
{ // }
public function update(Request $request, $id)
{ // }
public function destroy($id)
{ // }
}
use App\Http\Controllers\PostController;

Route::resource('posts', PostController::class);
web.php

if you want to choose certain function in the controller:

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

public function rules()


{ return[
'title=>'bail|requiredmin:5|max:100',
'content=>'required|min:10'
];
}

public function store(storePost $request)


{
$validated = $request->validated();
$post = new Blogspot();
$post->content = $validated->['content'];
$post->title = $validated->['title'];
$post->save();
}
Session Flash Messages
PostController.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

public function store(StorePost $request)


{
$validated = $request->validated();
$post = new Blogpost();
$post->title = $validated['title'];
$post->content = $validated['content'];
$post->fill;
$post->save();
}

• 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

public function edit($id)


{
return view('posts.edit'),['post' => BlogPost::findOrFail($id)]);
}

form.blade.php

<div><input type="text" name="title"> value="{{ old('title', optional($post ?? null)-


>title) }}"</div>
@error('title')
<div>{{$message}}</div>
@enderror
<div textarea name="content">{{ old('content', optional($post
?? null)->content) }}</div>
Update Action PostController.php

public function update(StorePost $request, $id)


{
$post = BlogPost::findOrFail($id);
$validated = $request->validated();
$post->fill($validated);
$post->save();

$request->session()->flash('status', 'Blog post was updated!');

return redirect()->route('posts.show', ['post'=>$post->id]);


Deleting Using Forms post.blade.php

<div>{{ $key }}.{{ post->title }}</div>


@else
<div style="background-color: silver">{{ $key }}.{{ $psot->title }}</div>
@endif
<div>
<form action="{{ route('posts.destroy', ['post'=> $post->id]) }}" method="POST">
@csrf
@method('DELETE')
<input type="submit" value="Delete!">
</form>
</div>
PostsController.php

public function destroy($id)


{
$post = BlogPost::findOrFail($id);
$post->delete();
session()->flash('status', 'Blog post was delete!');
return redirect()->route('posts.index');
}

• This method will deleted the data without physically deleting


them from the database, it is so called "soft delete".
Assets & Styling(Javascript, CSS,
Laravel Mix, Bootstrap)
Introduction to Laravel Mix
Installing Bootstrap CSS
Framework
composer require laravel/ui 3.0.0

php artisan ui bootstrap

php artisan ui:controllers

composer require laravel/ui 3.0.0


Using NPM & Compiling Assets
with Mix/Webpack
npm install

node -v

npm run dev


Including Assets in Views

<link rel="stylesheet" href="{{


asset(css/app.css) }}">
<script src="{{ asset('js/app.js') }}
defer></script>
<title> Laravel App -
@yeild('title')</title>
Versioned Assets (Cache
Improvements) webpack.mix.js

if)mix.inProduction()){
mix.version(); app.blade.php
}

<link rel="stylesheet" href="{{


mix(css/app.css) }}">
<script src="{{ mix('js/app.js') }}
defer></script>
<title> Laravel App -
@yeild('title')</title>

npm run prod


Introduction to Bootstrap CSS
Understanding CSS Flexbox
in General and in Bootstrap
example:

Layout Grid and Styling Header


<div class="container">
Bar <div class="row">
<div class="col">
1 of 2
</div>
<div class="col">
2 of 2
</div>
</div>
<div class="row">
<div class="col">
1 of 3
</div>
<div class="col">
2 of 3
</div>
<div class="col">
3 of 3
</div>
</div>
</div>
Styling Forms example:

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

<div class="alert alert-success" role="alert">


<h4 class="alert-heading">Well done!</h4>
<p>Aww yeah, you successfully read this important alert message. This
example text is going to run a bit longer so that you can see how spacing
within an alert works with this kind of content.</p>
<hr>
<p class="mb-0">Whenever you need to, be sure to use margin utilities to keep
things nice and tidy.</p>
</div>
One to Many Eloquent Relation
One to one Relation Migration

One to One assigning

One to One quering


One to Many Relation with
Migration

One to Many Assigning


relationship

One to Many Querying


relationship
Query
Lazy loading vs Eager Loading

While lazy loading delays the initialization of a resource, eager


loading initializes or loads a resource as soon as the code is
executed. Eager loading also involves pre-loading related entities
referenced by a resource.
Query Relationship existance
Query relationship Absence

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

Laravel's authentication facilities are made up of "guards"


and "providers". Guards define how users are authenticated
for each request.
Using Validation method
It is function to validates the incoming data
Authenticated Middleware
Laravel includes a middleware that verifies the user of your application
is authenticated. If the user is not authenticated, the middleware will
redirect the user to your application's login screen.
Middleware
middleware can be written to perform a variety
of tasks besides authentication
Assigning Middleware To Routes

Once the middleware has been defined in the HTTP


kernel, you may use the middleware method to
assign middleware to a route:.
Protecting Routes
to avoid access by anyone
Testing Routes
The tests to make sure that all of routes are using the correct
middleware and are not accessible without the correct auth or
permission.
Database Seeding
Basic
Data seeding is the process of populating a database with an initial set of data.
There are several ways this can be accomplished

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

Gates provide a simple, closure-based approach to


authorization while policies, like controllers, group
logic around a particular model or resource.
Closures that determine if a user is authorized to perform a given action and are typically
defined in the App\Providers\AuthServiceProvider class using the Gate facade.
Authorized() Helper in Controller
Helper Function
Use to add a feature into Laravel application that can be used
at multiple locations within controllers, views, or model
files.
Policies
classes that organize authorization logic around a particular
model or resource
Configuring locale and translation
overview
You may modify the default language for a single HTTP request
at runtime using the setLocale method provided by the App
facade:
Policy vs Gate
Policy Gate

can authorize actions using Policies Gates are Permissions

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.

are used to build reliable and extensible systems


Blade Component
Component Aliases
define a component alias with a string to the template path as
a typical @component
Caching
Laravel provides a robust and easy-to-use implementation
of caching and different caching backends
Storing data in cache
use the put method on the Cache facade to store items in
the cache:
Store if Not present

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

Using forever method to be used to store an item in the


cache permanently
Removing Items From The Cache

remove items
from the cache
using the forget
method
Laravel caching backends

Memcached
Database
Redis
File
Array
Cache Facade

a facade is a class that provides access


to an object from the container
How facades work
The machinery that makes this work is in the Facade class.
Laravel's facades, and any custom facades create, will extend the
base Illuminate\Support\Facades\Facade class.

The Facade base class makes use of the __callStatic() magic-


method to defer calls from your facade to an object resolved from
the container.
Cache Tags
Cache tags allow you to tag related items in the cache and then flush all cached
values that have been assigned a given tag.
Route Model Binding
route model binding provides a convenient way
to automatically inject the model instances
directly into your routes.
Routes Model type

Implicit model binding explicit model binding


Implicit Model Binding
automatically inject the model instance that has an ID matching the
corresponding value from the request URI.
Route Model Binding
a mechanism to inject a model instance into routes
Explicit Model Binding
using the router’s model method to specify the class for
a given parameter.

define your explicit model bindings in the boot method


of the app/Providers/RouteServiceProvider.php class:
File Storage and Uploading

Storage Facade

Disks Local (Default) Public S3

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

Used to define relationships where a single model is the parent to


one or more child models.

For example, imagine users of your application can "comment"


on posts and videos. Using polymorphic relationships, you may
use a single comments table to contain comments for both posts
and videos
Model Structure
Many to Many Polymorphic Eloquent Relation
( ((
Many-to-many polymorphic relations are slightly more complicated
than "morph one" and "morph many" relationships.

For example, a Post model and Video model could share a


polymorphic relation to a Tag model.

Using a many-to-many polymorphic relation in this situation would


allow your application to have a single table of unique tags that may
be associated with posts or videos.
Model Structure
Sending Mail
Laravel provides a clean, simple API over the popular
SwiftMailer library. Laravel provides drivers for SMTP,
Mailgun, Mandrill, Amazon SES, PHP's mail function,
and sendmail, allowing you to quickly get started sending
mail through a local or cloud based service of your
choice.
Generating Mailable
When building Laravel applications, each type of email sent by your
application is represented as a "mailable" class. These classes are
stored in the app/Mail directory.

create your first mailable class using the make:mail Artisan


command:
Writing Mailables
Mailable class configuration is done in several methods, including the
envelope, content, and attachments methods.

The envelope method returns an Illuminate\Mail\Mailables\Envelope object that


defines the subject and, sometimes, the recipients of the message.

The content method returns an Illuminate\Mail\Mailables\Content object that


defines the Blade template that will be used to generate the message content.
Then, when configuring the mailable Content definition within its content method, use
the markdown parameter instead of the view parameter:
Writing Mailables
Mailable class configuration is done in several methods, including the
envelope, content, and attachments methods.

The envelope method returns an Illuminate\Mail\Mailables\Envelope object that


defines the subject and, sometimes, the recipients of the message.

The content method returns an Illuminate\Mail\Mailables\Content object that


defines the Blade template that will be used to generate the message content.
Previewing Mailables In The Browser
When designing a mailable's template, it is convenient to quickly preview the
rendered mailable in your browser like a typical Blade template

For this reason, Laravel allows you to return any mailable directly from a route
closure or controller.

When a mailable is returned, it will be rendered and displayed in the browser,


allowing you to quickly preview its design without needing to send it to an actual
email address:
Queues and Background Processing

Controller

Web Server + Database


PHP
Mail::send()

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.

Create observers class for Product as shown in the command


below:
Event and Listeners

Events Listeners Subscribers

Registered SendEmailVerification CommentEventSubscribers

CommentPosted NotifyBlogPostAuthor

NotifyOtherCommentors

Handle only 1 event, Can handle many events,


Just a simple class
can be queued jobs cannot be queued jobd
Localization (Translation)
Laravel's localization features provide a convenient way to
retrieve strings in various languages, allowing you to easily
support multiple languages within your application.
Service Container
The Laravel service container is a powerful tool for managing class
dependencies and performing dependency injection. Dependency
injection is a fancy phrase that essentially means this: class dependencies
are "injected" into the class via the constructor or, in some cases, "setter"
methods.
Contracts
Laravel's Contracts are a set of interfaces that define the core services provided by
the framework. For example, a Illuminate\Contracts\Queue\Queue contract
defines the methods needed for queueing jobs, while the Illuminate\Contracts\
Mail\Mailer contract defines the methods needed for sending e-mail.
What is Postman in Laravel?

This package allows you to automatically generate a Postman collection based on


your API routes. It also provides basic configuration and support for bearer auth
tokens and basic auth for routes behind an auth middleware.
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.

All of Laravel's facades are defined in the


Illuminate\Support\Facades namespace. So,
we can easily access a facade like so:
How model serialization works
# Serializing to Array
To convert a model and its loaded relationships to an array, you should use the
toArray method. This method is recursive, so all attributes and all relations
(including the relations of relations) will be converted to arrays:
# Serializing to JSON
To convert a model to JSON, you should use the toJson method. Like toArray, the
toJson method is recursive, so all attributes and relations will be converted to
JSON. You may also specify any JSON encoding options that are supported by
PHP:
API Resource
To generate a resource class, you may use the make:resource Artisan command.
By default, resources will be placed in the app/Http/Resources directory of your
application. Resources extend the Illuminate\Http\Resources\Json\JsonResource
class:
API in Laravel
Route::method

middleware() Apply middlewares or


RouteServiceProvider middleware group

mapWebRoutes() mapApiRoutes() namespace() Set controller namespace

prefix() Add URL prefix


web.php api.php

name() Prefix all route names


Session Stateless

group() Apply all of the above to


Session Auth Token Auth these routes
Pagination
The paginate method counts the total number of records matched by the query before retrieving the
records from the database. This is done so that the paginator knows how many pages of records there
are in total. However, if you do not plan to show the total number of pages in your application's UI
then the record count query is unnecessary.
API Tokens
Once the api_token column has been added to your
users table, you are ready to assign random API tokens
to each user that registers with your application

You should assign these tokens when a User model is


created for the user during registration.

When using the authentication scaffolding provided by


the make:auth Artisan command, this may be done in
the create method of the RegisterController:
Testing APIs
Laravel also provides several helpers for testing JSON
APIs and their responses. For example, the json,
getJson, postJson, putJson, patchJson, deleteJson, and
optionsJson methods may be used to issue JSON
requests with various HTTP verbs

You may also easily pass data and headers to these


methods. To get started, let's write a test to make a
POST request to /api/user and assert that the expected
JSON data was returned:
Response Assertions
Laravel's Illuminate\Testing\TestResponse class provides a variety of custom
assertion methods that you may utilize when testing your application. These
assertions may be accessed on the response that is returned by the json, get, post,
put, and delete test methods
Available
Assertions

You might also like