• Tidak ada hasil yang ditemukan

Free E-Book Learning Laravel Tutorial

Gemilang Makmur .P

Academic year: 2023

Membagikan "Free E-Book Learning Laravel Tutorial"

Copied!
216
0
0

Teks penuh

About

Getting started with Laravel

Remarks

Laravel StackOverflow Slack Community

Featured Tutorial

Contribution Guidelines

Contribution Style Guide

About Laravel

Main Features

They connect to models to retrieve, create, or update data and display the results in views that contain the actual HTML structure of the application.

Blade Templating Engine

Routing & Middleware

Artisan

Eloquent ORM

Event Handling

Versions

Welcome to Laravel tag documentation!

Starter Guide

Getting Started

Laravel Views

Artisan

Syntax

Parameters

Introduction

List all registered routes filtered by multiple methods

Running Laravel Artisan commands using PHP code

Creating and registering new artisan command

Authentication

Multi Authentication

Authorization

With authorization, you can selectively allow users access to certain resources while denying access to others.

Using Gates

Authorizing Actions with Gates

Policies

Writing Policies

Authorizing Actions with Policies

Blade Templates

The Blade template engine allows us to create master templates and child templates that load content from master templates, we can have variables, loops and conditional statements inside the blade file.

Views: Introduction

In this case, the string passed to compact() corresponds to the name of the variable we want to pass to the view.

Control Structures

Conditionals

If' statements

Unless' statements

Loops

While' loop

Foreach' loop

Forelse' Loop

Echoing PHP expressions

Echoing a variable

Echoing an element in an array

Echoing an object property

Echoing the result of a function call

Checking for Existence

Raw echos

Including Partial Views

In general, an included page will have access to any variable that the calling page has access to. You can also pass an optional fourth argument to the @each directive to specify the view to display when the array is empty.

Layout Inheritance

View::make('otherpage') will produce the same html, except with the text "This is another page!". The extension command uses the same syntax as is used for View::make and @include, so the file.

Sharing data to all views

Using View::share

Using View::composer

Closure-based composer

Class-based composer

This parameter is a string, which matches the display names, for which the composer should be registered (* is a wildcard).

Execute arbitrary PHP code

Cashier

Laravel Cashier can be used for subscription invoicing by providing an interface to the subscription services of both Braintree and Stripe. In addition to basic subscription management, it can be used to manage coupons, subscription exchanges, quantities, cancellation deadlines and PDF invoice generation.

Stripe Setup

Change default routing behaviour in Laravel 5.2.31 +

Adding api-routes with other middleware and keep default web middleware

Collections

You may have used it without knowing, for example Model Queries fetching multiple records gives an example of Illuminate\Support\Collection.

Creating Collections

Nesting

Additions

Using Get to lookup value or return default

Using Contains to check if a collection satisfies certain condition

Using Pluck to extract certain values from a collection

Using Map to manipulate each element in a collection

Using sum, avg, min or max on a collection for statistical calculations

Sorting a collection

Sort()

SortBy()

SortByDesc()

Using reduce()

If all scores are greater than 50, the result is returned true; if less than 50, return false. The default value of $carry is zero, so we check this in our conditional value.

Using macro() to extend collections

Using Array Syntax

Common Issues & Quick Fixes

TokenMisMatch Exception

Constants

First you need to create a file constants.php and it is a good practice to create this file inside app/config/ directory.

Controllers

Basic Controllers

Controller Middleware

Resource Controller

The resource controller example shares the method name with those in the table below. This single route declaration creates multiple routes to handle a variety of actions on the resource.

Actions Handled By Resource Controller

Cron basics

Create Cron Job

Cross Domain Request

So we need to make sure that whatever headers we add must be correct, otherwise our APIs become vulnerable. To add the headers, we need to add the middleware to laravel which will add the appropriate headers and forward the requests.

CorsHeaders

Custom Helper function

You can put multiple helpers in one file (that's how Laravel does it) or you can separate them by name. Now you can use the document() function anywhere in your code, for example in blade templates.

CustomException class in Laravel

CustomException class in laravel

Database

Multiple database connections

Database Migrations

Migrations

What you can achieve by creating a new migration. And in the up method of your migration.

The migration files

Generating migration files

Inside a database migration

Running migrations

Rolling Back Migrations

Database Seeding

Running a Seeder

Creating a Seed

Inserting Data using a Seeder

Inserting data with a Model Factory

Seeding with MySQL Dump

Use laravel's helper function database_path() and add the directory and filename of the dump. Or you can run the Seeder for a single class using php artisan db:seed --class=UsersTableSeeder.

Using faker And ModelFactories to generate Seeds

  • BASIC SIMPLE WAY
  • USING Model Factories
  • Deploy Laravel 5 App on Shared Hosting on Linux Server
  • App on Shared Hosting on Linux Server
  • Directory Structure

By default, you should upload their app/code to the public_html folder in their shared hosting account. If you upload the entire application (folder) to the public_html folder on your shared hosting account.

Change default app directory

Override Application class

Calling the new class

Composer

Change the Controllers directory

Eloquent

Eloquent will automatically try to associate your model with a table that has a plural model name as above. It allows you to interact with database tables in an object-oriented manner using the ActiveRecord pattern.

Sub-topic Navigation

Persisting

But you can also create a record without even changing fillable attribute in your model by using

Deleting

Soft Deleting

To force delete a record, use the forceDelete() method which actually deletes the record from the database:.

Change primary key and timestamps

Throw 404 if entity not found

Cloning Models

Eloquent : Relationship

Querying on relationships

Inserting Related Models

Alternatively, there is also a create method that accepts a regular PHP array instead of an Eloquent model instance. Because relationships, like the Eloquent models themselves, also serve as powerful query builders, defining relationships as functions provides powerful capabilities for linking methods and executing queries.

Relationship Types

One to Many

One to One

How to associate between two models (example: User and Phone model)

If your database field name conforms to the Laravel standard, you do not need to specify a foreign key and local key in the relationship declaration.

Explanation

Many to Many

If keys other than these are to be used, it must be passed as the third and fourth parameters. Let's say whether to use other_role_id instead of role_id and other_permission_id instead of permission_id.

Polymorphic

The imageable_id column contains the ID value of the user or product, while the imageable_type column contains the class name of the owning model. You can also retrieve the owner of a polymorphic relationship from the polymorphic model by accessing the name of the method that executes the morphTo call.

Many To Many

Eloquent: Accessors & Mutators

Accessors and mutators let you format the values ​​of Eloquent attributes when you get or set them on model instances. In addition to custom accessors and mutators, Eloquent can also automatically cast date fields to Carbon instances or even stream text fields to JSON.

Defining An Accessors

For example, you may want to use Laravel encryption to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.

Getting Accessor

Defining a Mutator

Eloquent: Model

Making a Model Model creation

The file we are interested in is the latter since it is this file that we can decide how we want the table to look and include. For any predefined migration, we get an auto-incrementing ID column and a timestamp columns.

Model File Location

As you can see, it is relatively easy to create the model and migration for a table.

Model configuration

Update an existing model

Error Handling

Send Error report email

Catching application wide ModelNotFoundException

Events and Listeners

Using Event and Listeners for sending emails to a new registered user

Filesystem / Cloud Storage

Configuration

Basic Usage

Custom Filesystems

Creating symbolic link in a web server using SSH

Form Request(s)

Custom Requests (or Form Requests) are useful in situations when one wants to authorize &. Using Form Requests is trivial, one has to type the request class in the method.

Creating Requests

Using Form Request

Handling Redirects after Validation

Getting started with laravel-5.3

It should also mention any major topics within laravel-5.3 and link to relevant topics. Since the Documentation for laravel-5.3 is new, you may need to build initial versions of those related topics.

Installing Laravel

This section provides an overview of what laravel-5.3 is and why a developer might want to use it.

Via Laravel Installer

Be sure to put the $HOME/.composer/vendor/bin directory (or the equivalent directory for your OS) in your $PATH so that the laravel executable can be found by your system. Once installed, the new laravel command will create a new Laravel installation in the directory you specify.

Via Composer Create-Project

Setup

Server Requirements

Local Development Server

Hello World Example (Basic) and with using a view

We will create the new file in the resources/views folder and we will name it helloworld.blade.php. Now we open this new file and edit it by creating our Hello World phrase.

Hello World Example (Basic)

This file "helloworld" contains the HTML and maybe later even some PHP of the Helloworld text. We can add several different ways to get our point across as in the example below.

Web Server Configuration for Pretty URLs

Helpers

Array methods

String methods

Path mehods

Urls

HTML and Form Builder

Installation

Installation

Via Composer

Via the Laravel installer

To run the Laravel installer, you need to make sure that the Composer binaries folder is inside your $PATH variable. If not, edit your .bashrc, or if you're using ZSH, your .zshrc to include the path to your Composer provider directory.

Running the application

Once installed, this command will create a new Laravel installation in the directory you specify. a dot) instead of [foldername] to create the project in the current working directory without creating a sub-directory.

Using a different server

On *nix operating systems this can be achieved by. chown -R www-data:www-datastorage boot/cache chmod -R ug+rwx storage boot/cache. where www-data is the name and group of the web server user). The web server of your choice must be configured to serve content from your project's /public.

Requirements

Hello World Example (Using Controller and View)

You can serve your app using the following PHP Artisan command: php artisan serve; it shows you the address where you can access your application (usually defaults to http://localhost:8000). Alternatively, you can go directly to the appropriate location in your browser; in case you are using a server like XAMPP (or: http://localhost/hello-world/public/hello if you have installed your Laravel instance, hello-world, directly in your : after running the step 1 of this Hello Word from your command line interface, pointing to your .xampp/htdocs folder).

Installation using LaraDock (Laravel Homestead for Docker)

Installation Guide

It should also mention any major subjects within laravel-5.4, and link to the related topics. Since the Documentation for laravel-5.4 is new, you may need to create initial versions of those related topics.

Hello World Example With Views and Controller

The view

The controller

Edit that new file and write a new method hello that will display the view we created before. Now when we call the method hello of the controller HelloController, it will display the message.

The router

Introduction to laravel-5.2

It should also mention all major topics within laravel-5.1 and link to the related topics. Since the documentation for laravel-5.1 is new, you may need to create initial versions of these related topics.

Installation or Setup

  • Install LAMP
  • Install Composer
  • Install Laravel
  • Set Encryption Key
  • Create Apache VirtualHost
  • Access Laravel
  • Introduction to laravel-5.3

This section provides an overview of what laravel-5.1 is and why a developer might want to use it. Change 127.0.0.1 to the server ip and laravel.example.com to the domain name configured in Apache.

The $loop variable

Laravel Docker

Using Laradock

Laravel Packages

Intervention Image

Laravel generator

Laravel Socialite

Official Packages

Cashier

Envoy

Passport

Scout

Socialite

Getting started with Lumen

Macros In Eloquent Relationship

We can fetch one instance of hasMany relationship

Mail

Basic example

Middleware

Middleware are classes that can be assigned to one or more routes and are used to take actions in the early or late stages of the request cycle. A "Before" middleware runs before the controller's action code; while an “After” middleware is executed after the request has been handled by the application.

Defining a Middleware

Before vs. After Middleware

Route Middleware

Multiple DB Connections in Laravel

Initial Steps

Using Schema builder

Using DB query builder

Using Eloquent

From Laravel Documentation

Naming Files when uploading with Laravel on Windows

Generating timestamped file names for files uploaded by users

Observer

Creating an observer

Pagination

Pagination in Laravel

When the page method is called, you get an instance of Illuminate\Pagination\LengthAwarePaginator, while when you call The HTML generated by the links method is fully compatible with Bootstrap's CSS framework.

Changing pagination views

Permissions for storage

Policies

Creating Policies

Queues

Use-cases

Queue Driver Configuration

Remove public from URL in laravel

How to do that?

Remove the public from url

Requests

Getting input

Requests

Obtain an Instance of HTTP Request

Request Instance with other Parameters from routes in controller method

Route Model Binding

Implicit Binding

Explicit Binding

Routing

Basic Routing

Routes pointing to a Controller method

A route for multiple verbs

Route Groups

Named Route

Generate URL using named route

Route Parameters

Optional Parameter

Required Parameter

Accessing the parameter in controller

Catch all routes

Catching all routes except already defined

Routes are matched in the order they are declared

Case-insensitive routes

Seeding

As with all crafting commands, you have access to a wide range of methods that can be found in the api documentation.

Inserting data

Using the DB Facade

Via Instantiating a Model

Using the create method

Using factory

Seeding && deleting old data and reseting auto-increment

Calling other seeders

Creating a Seeder

You can also specify the start of a specific seeder class to be started individually with the --class option.

Safe reseeding

Services

Therefore, the next step is to register your service in the Service Container. When you register your service in the Service Container, you don't have to create a new object every time you need it.

Services

Binding an Interface To Implementation

Binding an Instance

Binding a Singleton to the Service Container

It can be used as a dependency injection container and a registry for the application by defining bindings to Service Providers. Service providers are classes where we define how our service classes will be created through the application, bootstrap their configuration, and bind interfaces to implementations Services are classes that wrap one or more logically related tasks together.

Using the Service Container as a Dependency Injection Container

Socialite

To use it, make sure the alias array (also in your config\app.php) has the following code.

Basic Usage - Facade

Basic Usage - Dependency Injection

Socialite for API - Stateless

Sparkpost integration with Laravel 5.4

SAMPLE .env file data

Task Scheduling

Creating a task

The $description property is Artisan's help/usage display next to your command when it is made available.

Making a task available

Scheduling your task

Setting the scheduler to run

Testing

PHPUnit is configured using the phpunit.xml file, which is located in the root directory of every new Laravel application. In the testBasicExample() method, we visit the page's index page and make sure we see the text.

Test without middleware and with a fresh database

The tests directory, also in the root directory, contains the individual test files that hold the logic for testing each part of your application.

Database transactions for mutliple database connection

Testing setup, using in memory database

Token Mismatch Error in AJAX

Here are some of the examples ie No _token on headers, No _token passed data when using Ajax, permission issue on storage path, an invalid session storage path.

Setup Token on Header

Set token on tag

Check session storage path & permission

Use _token field on Ajax

Read Using Field Aliases in Eloquent online: https://riptutorial.com/laravel/topic/7927/use-fields-aliases-in-eloquent.

Useful links

Laravel Ecosystem

Education

Podcasts

Valet

Valet link

Laravel Valet makes all pages available in a *.dev domain by concatenating folder names with domain names. After running the link command, you can access the site in your browser at http://awesome-blog.dev.

Valet park

Valet links

Referensi

Dokumen terkait