0% found this document useful (0 votes)
8 views52 pages

Laravel New

This document provides an overview of PHP, an open-source, server-side scripting language used for web development. It covers key features of PHP, including performance, open-source nature, syntax familiarity, and support for various databases, as well as its object-oriented programming concepts like classes, inheritance, and magic methods. Additionally, it discusses exception handling, visibility, and the use of predefined variables in PHP.

Uploaded by

harshadshukla23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views52 pages

Laravel New

This document provides an overview of PHP, an open-source, server-side scripting language used for web development. It covers key features of PHP, including performance, open-source nature, syntax familiarity, and support for various databases, as well as its object-oriented programming concepts like classes, inheritance, and magic methods. Additionally, it discusses exception handling, visibility, and the use of predefined variables in PHP.

Uploaded by

harshadshukla23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

MSC(IT & CA ) SEM 1 LARAVEL

PREPARED BY:

PREPARED BY:
PRO.PRASHIL MAHETA

BY :PLAZMA INSTITUTE

PLAZMA INSTITUTE Page 1


MSC(IT & CA ) SEM 1 LARAVEL
Q - 1 : What is PHP?

 Ans : PHP is an open-source, interpreted, and object-oriented scripting language that can
be executed at the server-side. PHP is well suited for web development. Therefore, it is
used to develop web applications (an application that executes on the server and
generates the dynamic page.).

 PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 8 is
the latest version of PHP.

 Some important points need to be noticed about PHP are as followed:

 PHP stands for Hypertext Preprocessor.

• PHP is an interpreted language, i.e., there is no need for compilation.

• PHP is faster than other scripting languages, for example, ASP and JSP.

• PHP is a server-side scripting language, which is used to manage the dynamic


content of the website.

• PHP can be embedded into HTML.

• PHP is an object-oriented language.

• PHP is an open-source scripting language.

• PHP is simple and easy to learn language.

Q – 2 : Explain PHP features .


Ans :PHP is very popular language because of its simplicity and open source. There are
some important features of PHP given below:

PLAZMA INSTITUTE Page 2


MSC(IT & CA ) SEM 1 LARAVEL

1) Performance:
 PHP script is executed much faster than those scripts which are written in other
languages such as JSP and ASP. PHP uses its own memory, so the server workload
and loading time is automatically reduced, which results in faster processing speed
and better performance.

2) Open Source:
 PHP source code and software are freely available on the web. You can develop all
the versions of PHP according to your requirement without paying any cost.
 All its components are free to download and use.

3) Familiarity with syntax:


 PHP has easily understandable syntax. Programmers are comfortable coding with it.

4) Embedded

 PHP code can be easily embedded within HTML tags and script.

5) Platform Independent:
 PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP
application developed in one OS can be easily executed in another OS also.

6) Database Support:
 PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.

7) Error Reporting-
 PHP redefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.

8) Loosely Typed Language:


 PHP allows us to use a variable without declaring its data type. It will be taken
automatically at the time of execution based on the type of data it contains on its
value.

9) Web servers Support:


 PHP is compatible with almost all local servers used today like Apache, Netscape,
Microsoft IIS, etc.

10) Security:
 PHP is a secure language to develop the website. It consists of multiple layers of
security to prevent threads and malicious attacks.

11) Control:
 Different programming languages require long script or code, where as PHP can do
the same work in a few lines of code. It has maximum control over the websites like
you can make changes easily whenever you want.

PLAZMA INSTITUTE Page 3


MSC(IT & CA ) SEM 1 LARAVEL
12) A Helpful PHP Community:
 It has a large community of developers who regularly updates documentation,
tutorials, online help, and FAQs. Learning PHP from the communities is one of the
significant benefits.

13) 8i Web Development


 PHP is widely used in web development nowadays. PHP can develop dynamic
websites easily. But you must have the basic the knowledge of following
technologies for web development as well.
 HTML,CSS, JavaScript ,Ajax, XML and JSON, jQuery
 Prerequisite
 Before learning PHP, you must have the basic knowledge of HTML, CSS ,and
JavaScript. So, learn these technologies for better implementation of PHP.

HTML-HTML is used to design static webpage.


CSS-CSS helps to make the webpage content more effective and attractive.
JavaScript-Java Script is used to design an interactive website.

Q : 3 Explain PHP with oops concept.


1) Class
 A class is an entity that determines how an object will behave and what the object will contain.
In other words, it is a blueprint or a set of instruction to build a specific type of object.
 In PHP, declare a class using the class keyword, followed by the name of the class and a set of
curly braces ({}).
 Syntax to Create Class in PHP :

<?php

Class My Class{

//Class properties and methods go here

}
2) Properties :
 Properties
?> Class member variables are called "properties". You may also see them referred to
using other terms such as "attributes" or "fields", but for the purposes of this reference we will
use "properties". They are defined by using one of the keywords public, protected, or private,
followed by a normal variable declaration.
 This declaration may include an initialization, but this initialization must be a constant value--
that is, it must be able to be evaluated at compile time and must not depend on run-time
information in order to be evaluated.

3) Class
 Constants It is possible to define constant values on a per-class basis remaining the same and
unchangeable. Constants differ from normal variables in that you don't use the $ symbol to
declare or use them. The default visibility of class constants is public. It's also possible for
interfaces to have constants.
PLAZMA INSTITUTE Page 4
MSC(IT & CA ) SEM 1 LARAVEL

<?php

Class My Class{

Const geet='constant value';

Function show Constant(){

Echo self::geet;

4) Auto loading Classes

 Many developers writing object-oriented applications create one PHP source file
per class definition. One of the biggest annoyances is having to write a long list of
needed includes at the beginning of each script (one for each class).

<?php

spl_auto load_register(function($class_name){

include $class_name.'.php';

});

$ obj=newMyClass1();

$ obj2=newMyClass2();

?>

5) Constructors and Destructors Constructor


 void __construct ([ mixed $args = "" [, $... ]] ) PHP 5 allows developers to declare constructor
methods for classes. Classes which have a constructor method call this method on each
newly-created object, so it is suitable for any initialization that the object may need before it
is used.

6) Destructor
 void __destruct ( void ) PHP 5 introduces a destructor concept similar to that of other object-
oriented languages, such as C++.
 The destructor method will be called as soon as there are no other references to a particular
object, or in any order during the shutdown sequence.
 Like constructors, parent destructors will not be called implicitly by the engine. In order to run
a parent destructor, one would have to explicitly call parent::__destruct() in the destructor
body.

PLAZMA INSTITUTE Page 5


MSC(IT & CA ) SEM 1 LARAVEL
 Also like constructors, a child class may inherit the parent's destructor if it does not
implement one itself. The destructor will be called even if script execution is stopped using
exit().
 Calling exit() in a destructor will prevent the remaining shutdown routines from executing.

7) Visibility
 The visibility of a property, a method or (as of PHP 7.1.0) a constant can be defined by
prefixing the declaration with the keywords public, protected or private.
 Class members declared public can be accessed everywhere.
 Members declared protected can be accessed only within the class itself and by inheriting and
parent classes. Members declared as private may only be accessed by the class that defines
the member.
 Property Visibility :
 Class properties must be defined as public, private, or protected. If declared using var, the
property will be defined as public.

 Method Visibility
 Class methods may be defined as public, private, or protected. Methods declared without
any explicit visibility keyword are defined as public.

 Constant Visibility
 As of PHP 7.1.0, class constants may be defined as public, private, or protected. Constants
declared without any explicit visibility keyword are defined as public.

8) Object Inheritance
 Inheritance is a well-established programming principle, and PHP makes use of this
principle in its object model.
 This principle will affect the way many classes and objects relate to one another.
 This is useful for defining and abstracting functionality, and permits the implementation
of additional functionality in similar objects without the need to re-implement all of the
shared functionality.

9) Scope Resolution Operator (::)


 The Scope Resolution Operator (also called PaamayimNekudotayim) or in simpler terms, the
double colon, is a token that allows access to static, constant, and overridden properties or
methods of a class.
 When referencing these items from outside the class definition, use the name of the class.

10) Static Keyword :


 Declaring class properties or methods as static makes them accessible without needing an
instantiation of the class.
 A property declared as static cannot be accessed with an instantiated class object (though a
static method can).
 Static methods
 Because static methods are callable without an instance of the object created, the pseudo
variable $this is not available inside the method declared as static.

PLAZMA INSTITUTE Page 6


MSC(IT & CA ) SEM 1 LARAVEL
11) Predefined Variables
 Super globals — Built-in variables that are always available in all scopes
 $GLOBALS — References all variables available in global scope
 $_SERVER — Server and execution environment information
 $_GET — HTTP GET variables
 $_POST — HTTP POST variables
 $_FILES — HTTP File Upload variables
 $_REQUEST — HTTP Request variables
 $_SESSION — Session variables
 $_ENV — Environment variables
 $_COOKIE — HTTP Cookies
 $php_error msg — The previous error message
 $http_response_header — HTTP response headers
 $argc — The number of arguments passed to script
 $argv — Array of arguments passed to script

12) Exceptions
 PHP try and catch are the blocks with the feature of exception handling, which contain the
code to handle exceptions. They play an important role in exception handling.
 There is one more important keyword used with the try-catch block is throw. The throw is a
keyword that is used to throw an exception.
 Each try block must have at least one catch block. On the other hand, a try block can also
have multiple catch blocks to handle various classes of exception.

 try
 The try block contains the code that may contain an exception. An exception raised in try
block during runtime is caught by the catch block. Therefore, each try block must have at
least one catch block. It consists of the block of code in which an exception can occur.
Following points needs to be noted about the try:

• The try block must be followed by a catch or finally block.


• A try block must have at least one catch block
. • There can be multiple catch blocks with one try block.

 Catch
 The catch block catches the exception raised in the try block. It contains the code to catch the
exception, which is thrown by throw keyword in the try block. The catch block executes when
a specific exception is thrown. PHP looks for the matching catch block and assigns the
exception object to a variable. Following points to be noted about the catch:

 There can be more than one catch block with a try.


• The thrown exception is caught and resolved by one or more catch.
• The catch block is always used with a try block. It cannot be used alone.
• It comes just after the try block.

 throw
 It is a keyword, which is used to throw an exception. Note that one throw at least has one
"catch block" to catch the exception.

PLAZMA INSTITUTE Page 7


MSC(IT & CA ) SEM 1 LARAVEL
 Finally
 It is a block that contains the essential code of the program to execute. The finally block is also
used for clean-up activity in PHP. It is similar to the catch block, which is used to handle
exception. The only difference is that it always executes whether an exception is handled or
not.

13) Class Abstraction


 PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be
instantiated, and any class that contains at least one abstract method must also be abstract.
Methods defined as abstract simply declare the method's signature - they cannot define the
implementation.
 When inheriting from an abstract class, all methods marked abstract in the parent's class
declaration must be defined by the child;

14) Object Interfaces


 Object interfaces allow you to create code which specifies which methods a class must
implement, without having to define how these methods are implemented.

15) Overloading
 Overloading in PHP provides means to dynamically "create" properties and methods. These
dynamic entities are processed via magic methods one can establish in a class for various
action types. The overloading methods are invoked when interacting with properties or
methods that have not been declared or are not visible in the current scope.
 Note : All overloading methods must be defined as public.
 Property overloading
 public void __set ( string $name, mixed $value )
 public mixed __get ( string $name )
 public bool __isset ( string $name )
 public void __unset ( string $name )

16) Magic Methods


 The function names
__construct(), __destruct(), __call(), __call Static(), __get(), __set(), __isset(), __unset(),
__sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo()
are magical in PHP classes. You cannot have functions with these names in any of your classes
unless you want the magic functionality associated with them

__toString()
public string __toString ( void )

 The __toString() method allows a class to decide how it will react when it is treated like a
string.

__invoke()
mixed __invoke ([ $... ] )
 The __invoke() method is called when a script tries to call an object as a function .

PLAZMA INSTITUTE Page 8


MSC(IT & CA ) SEM 1 LARAVEL
__set_state()
static object __set_state ( array $properties )
 This static method is called for classes exported by var_export() since PHP 5.1.0.The only
parameter of this method is an array containing exported properties in the form
array('property' => value, ...).

__debugInfo()
 array __debugInfo ( void ) This method is called by var_dump() when dumping an object to
get the properties that should be shown.

17) Final Keyword :


 PHP 5 introduces the final keyword, which prevents child classes from overriding a method by
prefixing the definition with final. If the class itself is being defined final then it cannot be
extended.

18) Object Cloning


 Creating a copy of an object with fully replicated properties is not always the wanted
behavior. A good example of the need for copy constructors.
 An object copy is created by using the clone keyword (which calls the object's __clone()
method if possible). An object's __clone() method cannot be called directly.

 void __clone ( void )


 Once the cloning is complete, if a __clone() method is defined, then the new ly created
object's __clone() method will be called, to allow any necessary properties that need to
be changed.

19)Type Hinting
 Type declarations allow functions to require that parameters are of a certain type at call time.
If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a
recoverable fatal error, while PHP 7 will throw a Type Error exception. To specify a type
declaration, the type name should be added before the parameter name. The declaration can
be made to accept NULL values if the default value of the parameter is set to NULL.

Q : 4 What is bootstrap ?
Ans : Bootstrap is an Open Source product from Mark Otto and Jacob Thornton who, when
initially released were both employees at Twitter.
 Since Bootstrap launched in August, 2011 it has taken off in popularity. It has evolved away
from being an entirely CSS driven project to include a host of JavaScript plugins, and icons
that go hand in hand with forms and buttons.
 At its base, it allows for responsive web design, and features a robust 12 column, 940px wide
grid. One of the highlights is the build tool on http://getbootstrap.com website where you
can customize the build to suit your needs, choosing what CSS and JavaScript features that
you want to include on your site.
 All of this, allows front-end web development to be catapulted forward, building on a stable
foundation of forward-looking design, and development.
 Getting started with Bootstrap is as simple as dropping some CSS and JavaScript into the root
of your site.

PLAZMA INSTITUTE Page 9


MSC(IT & CA ) SEM 1 LARAVEL
 File Structure :

 The Bootstrap download includes three folders: css, js and img.

 Basic HTML Template :


<!DOCTYPE html>

<html>

<head>

<title>Bootstrap101Template</title>

</head>

<body>

<h1>Hello world!</h1>

</body>

</html>

 Global Styles
 With Bootstrap, a number of items come prebuilt. Instead of using the old reset block that was
part of the Bootstrap 1.0 tree, Bootstrap 2.0 uses Normalize.css, a project from Nicolas Gallagher
that is part of the HTML5 Boilerplate. This is included in the Boot‐ strap.css file. I

 Default Grid System


 The default Bootstrap grid system utilizes 12 columns, making for a 940px wide container without
responsive features enabled. With the responsive CSS file added, the grid adapts to be 724px and
1170px wide depending on your viewport. Below 767px view‐ ports, for ex‐ ample, on tablets and
smaller devices the columns become fluid and stack vertically. At the default width, each column
is 60 pixels wide, offset 20 pixels to the left.

PLAZMA INSTITUTE Page 10


MSC(IT & CA ) SEM 1 LARAVEL

 Basic Grid HTML


 To create a simple layout, create a container with a div that has a class of .row, and add the
appropriate amount of .span* columns. Since we have 12-column grid, we just need to have the
amount of .span* columns add up to twelve. We could use a 3-6-3 layout,4-8, 3-5-4, 2-8- 2, we
could go on and on, but I think you get the list.

 Basic Grid Layout :

<div class="row">

<div class="span8">...</div>

<div class="span4">...</div>

</div>
 Offsetting Columns
 You can move columns to the right using the .offset* class. Each class moves the span over that
width. So an .offset2 would move a .span7 over two columns.

 Offsetting Columns:

<div class="row">

<div class="span2">...</div>

<div class="span7offset2">...</div>

</div>

 Nesting Columns
 To nest your content with the default grid, inside of a .span*, simply add a new .row with enough
.span* that add up the number of spans of the parent container.

PLAZMA INSTITUTE Page 11


MSC(IT & CA ) SEM 1 LARAVEL
<div class="row">

<div class="span9">

Level1column

<div class="row">

<div class="span6">Level2</div>

<divclass="span3">Level2</div>

</div>

</div>

</div>

 Container Layouts

 To add a fixed width, centered layout to your page, simply wrap the content in <div class=
“container”>…..</div> If you would like to use a fluid layout, but want to wrap everything in a
container, use the following: <div class =”container-fluid”>….</div>Using a fluid layout is great
when you are building applications, administration screens and other related projects.

 Responsive Design
 Responsive Design to turn on the responsive features of Bootstrap, you need to add a meta tag to
the of your webpage. If you haven’t downloaded the compiled source, you will also need to add
the responsive CSS file. An example of required files looks like this:

 Responsive Meta Tag and CSS :


<!DOCTYPE html>

<html>

<head>

<title>My amazing Bootstrap site!</title>

<metaname="viewport"content="width=device-width,initial-scale=1.0">

 What Is<linkhref="/css/bootstrap.css"rel="stylesheet">
Responsive Design?
 Responsive design is a method for taking all of the existing content that is on the page, and
<linkhref="/css/bootstrap-responsive.css"rel="stylesheet">
optimizing it for the device that is viewing it.
 For example, the desktop not only gets the normal version of the website, but might get also get a
</head>
widescreen layout, optimized for the larger displays that many people have attached to their
computers. Tablets get an optimized layout, taking advantage of the portrait or landscape layouts of
those devices.

PLAZMA INSTITUTE Page 12


MSC(IT & CA ) SEM 1 LARAVEL
 And then with phones, you can target the much narrower width of phones. To target these different
widths, Bootstrap uses CSS media queries to measure the width of the browser viewport, and then
using conditionals, change which parts of the style sheets are loaded. Using the width of the browser
viewport, Bootstrap can then optimize the content using a combination of ratios, widths, but mostly
falls on min width and max-width properties.

Q : 5 explain implementation of bootstrap .


Ans : 1) Tables

 One of my favorite parts of Bootstrap is the nice way that tables are handled. I do a lot of work
looking at and building tables, and the clean layout is great feature that’s included in Bootstrap
right off the bat. Bootstrap supports the following elements:

 Types of table :
a) Optional Table Classes
b) Striped Table
c) Bordered Table
d) Hover Table
e) Table Row Classes

2) Forms:

 Another one of the highlights of using Bootstrap is the attention that is paid to forms. As a web
developer, one of my least favorite things to do is style forms.
 Bootstrap makes it easy to do with the simple HTML markup and extended classes for different
styles of forms.

3) Buttons :

 One of my favorite features of Bootstrap is the way that buttons are styled. Dave Winner ,inventor
of RSS, and big fan of Bootstrap has this to say about it: That this is needed, desperately needed, is
indicated by the incredible uptake of Bootstrap.
 I use it in all the server software I’m working on. And it shows through in the templating language
I’m developing, so everyone who uses it will find it’s “just there” and works, any‐ time you want to
do a Bootstrap technique.

PLAZMA INSTITUTE Page 13


MSC(IT & CA ) SEM 1 LARAVEL
 Nothing to do, no libraries to include. It’s as if it were part of the hardware. Same approach that
Apple took with the Mac OS in 1984.

4)Image

 Images have three classes to apply some simple styles. They are .img-rounded that addsborder-
radius:6px to give the image rounded corners, .img-circle that adds makes the entire image a circle
by adding border-radius:500px making the image round, and lastly, ingpolaroid, that adds a bit of
padding and a grey border.

<img src="..."class="img-rounded">

<img src="..."class="img-circle">

<img src="..."class="img-polaroid">

5) Glyphicon

 Attribution Users of Bootstrap are fortunate to use the Glyphicons free of use on Bootstrap
projects. The developers have asked that you use a link back to Glyphicons when practical.
 Usage To use the icons, simply use an tag with the name spaced .icon- class. For example ,if you
wanted to use the edit icon, you would simply add the .icon-edit class to the tag

<I class="icon-edit"></i>

6) Pagination :
 Bootstrap handles pagination like a lot of interface elements, an unordered list, with wrapper
<div>
 that has a specific class that identifies the element. In the basic form, adding pagination do the
parent<div> creates a row of bordered links. Each of the list items can be additionally styled by
using the .disabled or .active class.

PLAZMA INSTITUTE Page 14


MSC(IT & CA ) SEM 1 LARAVEL
 Pagination Code Example :
<div class="pagination">

<ul>

<li><a href="#">Prev</a></li>

<li><a href="#">1</a></li>

<li><a href="#">2</a></li>

<li><a href="#">3</a></li>

<li><a href="#">4</a></li>

<li><a href="#">Next</a></li>

</ul>

</div>

 Labels
 Labels and Badges are great for offering counts, tips, or other markup for pages. Another one of
my favorite little Bootstrap touches.

 Badges

 Badges are similar to labels, the primary difference is that they have more rounded
corners. The colors of badges reflect the same classes as labels.

 Typographic Elements :
 In addition to buttons, labels, forms, tables and tabs, Bootstrap has a few more elements for
basic page layout. The hero unit is a large, content area that increased the size of headings, and
adds a lot of margin for landing page content. To use, simply create a container <div>with the
class of .hero-unit. In addition to a larger <h1>all the font weight is reduced to 200.

PLAZMA INSTITUTE Page 15


MSC(IT & CA ) SEM 1 LARAVEL

 Thumbnails :
 A lot of sites need a way to layout images in a grid, and Bootstrap has an easy way to do this. At
the simplest, you add an <a>tag with the class of .thumbnail around an image.
 This adds four pixels of padding, and a grey border. On hover, an animated glow is added around
the image.

 Alerts :
Alerts provide a way to style messages to the user. The default alert is created by creating a wrapper
<div> and adding a class of .alert.

PLAZMA INSTITUTE Page 16


MSC(IT & CA ) SEM 1 LARAVEL
Q – 6: what is Laravel ? Explain with its features.
Ans :Laravel is a free open-source PHP framework.

 Laravel is created by Taylor atwell.


 Laravel intentent for the development of web application following Mode, View, Controller
architecture Pattern (MVC). Laravel is the powerful MVC PHP framework design for developer
who need a simple toolkit to create full feature we app. Laravel is MVC framework with bundles
migration and an instance CLR.
 Laravel offers a rawboust set of tools and a application architecture that in co-operates many of
the best features of framework like code engine, asp.net, MVC, etc.. Laravel has very richest of
feature which will boost the speed of web development.
 Features:
1. Modularity:
 Laravel was built on top of over 20 different libraries and is itself split into individual modules.
Tightly integrated with Composer dependency manager, these components can be updated
with ease.

2. Testability:

 Built from the ground up to ease testing, Laravel ships with several helpers that let you visit
routes from your tests, crawl the resulting HTML, ensure that methods are called on certain
classes, and even impersonate authenticated users in order to make sure the right code is run
at the right time.

3 . Routing:
 Laravel gives you a lot of flexibility when you define the routes of your application. For
example, you could manually bind a simple anonymous function to a route with an HTTP and
HTTPS verb, such as GET, POST, PUT, or DELETE.

4. Configuration management:
 More often than not, your application will be running in different environments, which means
that the database or email server credential's settings or the displaying of error messages will
be different when your app is running on a local development server to when it is running on a
production server

5. Query builder and ORM:


 Laravel ships with a fluent query builder, which lets you issue database queries with a PHP
syntax, where you simply chain methods instead of writing SQL.

6 . Schema builder, migrations, and seeding:


 Also inspired by Rails, these features allow you to define your database schema in PHP code
and keep track of any changes with the help of database migrations.

7 .Template engine :
 Partly inspired by the Razor template language in ASP.NET MVC, Laravel ships with Blade, a
lightweight template language with which you can create hierarchical layouts with predefined blocks
in which dynamic content is injected.

PLAZMA INSTITUTE Page 17


MSC(IT & CA ) SEM 1 LARAVEL

8. E-mailing:
 With its Mail class, which wraps the popular Swift Mailer library, Laravel makes it very easy to send
an e-mail, even with rich content and attachments from your application. Laravel also comes with
drivers for popular e-mail sending services such as Send Grid, Mail gun, and Mandrill.

9 Authentication:
 Since user authentication is such a common feature in web applications, out of the box
Laravel comes with a default implementation to register, authenticate, and even send
password reminders to users.

10 . Queues:
 Laravel integrates with several queue services, such as Amazon SQS, Beanstalkd, and
IronMQ, to allow you to delay resource-intensive tasks, such as the e-mailing of a large
number of users, and run them in the background, rather than keep the user waiting for the
task to complete.

11. Event and command bus:


 It is easy to dispatch events handle command and act in different point in your application
life cycle.

Q – 6 : Explain MVC architecture.


Ans : MVC means Model View Controller. MVC is a software architecture patterns for implementing
user interface on computer.

 It provides given software application into three inter connected part so, as to separate internal
represented of information from the way three information is presented to or accepted from the
user.
 MVC express the “Core OF the Solution to A problem while allowing is to be adapted for each
System”. The model directly manages the data login and rules for the application The central
component of MVC the Capture behavior of application
 The controller accept input and convert it to a command for the model and view.
 In addition to dividing the application into three kinds of component.
 The MVC Design define the interaction between them
 A model store data that is retrieved according to command from the controller and display in the
view. A view generates new output to the user based on changes in the model.
 Controller can send command to the model to update the models state
 It can also send command to this its associated view to change the user views presentation of the
model. A view can be any output regression of information such as a chat or diagram.
 The file extension of the view, either blade.php or single.php, simply.php, determines whether or
not Laravel treats your view as a blade template or not.

PLAZMA INSTITUTE Page 18


MSC(IT & CA ) SEM 1 LARAVEL
 MVC architecture :

Q 7 : Installation of Laravel.
 Using the installer:
1. This is the easiest way to get composer set up on your machine.

2. Download and run Composer-setpu.exe.

3. It will install the latest composer version and set up your path so that you can call composer from
any directory in your command line.

 Finding and installing new packages


 Via Composer Create-project.
 Alternatively, you may also install Laravel by issuing the composer create-project command in
your terminal:
 Composer create-project—prefer-dist Laravel/Laravel bolg”9.*”
 Basic Requirements For Laravel.

PLAZMA INSTITUTE Page 19


MSC(IT & CA ) SEM 1 LARAVEL

Version PHP(*) Release Bug Fixes Until Security Fixes Until

6 (LTS) 7.2-8.0 September3rd, 2019 January25th, 2022 September6th,2022

7 7.2-8.0 March3rd, 2020 October6th,2020 March3rd,2021

8 7.3-8.1 September8th,2020 July26th,2022 January24th, 2023

9 8.0-8.1 February8th,2022 August8th, 2023 February8th,2024

10 8.1 February7th,2023 August7th, 2024 February7th,2025

Q – 8 Explain configuration in laravel.


Ans :All of the configuration files for the Laravel framework are stored in the config directory. Each
option is documented, so feel free to look through the files and get familiar with the options
available to you.

 Environment configuration :
 It is often helpful to have different configuration values based on the environment the
application is running in. For example, you may wish to use a different cache driver locally than
you do on your production server. It's easy using environment-based configuration.

 Protecting Sensitive Configuration :


 For "real" applications, it is advisable to keep all of your sensitive configuration out of your
configuration files. Things such as database passwords, Stripe API keys, and encryption keys
should be kept out of your configuration files whenever possible.
 So, where should we place them? Thankfully, Laravel provides a very simple solution to
protecting these types of configuration items using "dot" files. First, configure your application to
recognize your machine as being in the local environment.
 Next, create a .env.local.php file within the root of your project, UNIT-2 Introduction to Laravel,
Artisan, Route and Controller Configuration 68 Prepared by: Prof. Hardik Chavda which is usually
the same directory that contains your composer.json file.
 The .env.local.php should return an array of key-value pairs, much like a typical Laravel
configuration file.

 Maintenance mode :
 When your application is in maintenance mode, a custom view will be displayed for all routes
into your application.
 This makes it easy to "disable" your application while it is updating or when you are performing
maintenance.
 A call to the App::down method is already present in your app/start/global.php file. The response
from this method will be sent to users when your application is in maintenance mode.

 Database configuration :
 Almost every modern web application interacts with a database.

PLAZMA INSTITUTE Page 20


MSC(IT & CA ) SEM 1 LARAVEL
 Laravel makes interacting with databases extremely simple across a variety of supported
databases using raw SQL, a fluent query builder, and the Eloquent ORM. Currently, Laravel
provides first-party support for five databases:

Q : 9 Explain project structure.


 The default Laravel application structure is intended to provide a great starting point for both
large and small applications. Of course, you are free to organize your application however you
like.
 Laravel imposes almost no restrictions on where any given class is located - as long as Composer
can auto load the class.
 The Root Directory The root directory of a fresh Laravel installation contains a variety of
directories: The app directory, as you might expect, contains the core code of your application.
 We'll explore this directory in more detail soon. The bootstrap directory contains a few files that
bootstrap the framework and configure auto loading, as well as a cache directory that contains a
few framework generated files for bootstrap performance optimization.
 The config directory, as the name implies, contains all of your application's configuration files.
The database directory contains your database migration and seeds.
 If you wish, you may also use this directory to hold an SQLite database. The public directory
contains the front controller and your assets (images, JavaScript, CSS, etc.).
 The resources directory contains your views, raw assets (LESS, SASS, Coffee Script), and
localization files. The storage directory contains compiled Blade templates, file based sessions,
file caches, and other files generated by the framework.
 This directory is segregated into app, framework, and logs directories. The app directory may be
used to store any files utilized by your application.
 The framework directory is used to store framework generated files and caches. Finally, the logs
directory contains your application's log files.
 The tests directory contains your automated tests. An example PHP Unit is provided out of the
box. The vendor directory contains your Composer dependencies.

 The App Directory :

 The "meat" of your application lives in the app directory. By default, this directory is name
spaced under App and is auto loaded by Composer using the PSR-4 auto loading standard.
The app directory ships with a variety of additional directories such as Console, Http, and
Providers.
 Think of the Console and Http directories as providing an API into the "core" of your
application. The HTTP protocol and CLI are both mechanisms to interact with your
application, but do not actually contain application logic.
 In other words, they are simply two ways of issuing commands to your application. The
Console directory contains all of your Artisan commands, while the Http directory contains
your controllers, middleware, and requests.
 The Events directory, as you might expect, houses event classes.
 Events may be used to alert other parts of your application that a given action has occurred,
providing a great deal of flexibility and decoupling.
 The Exceptions directory contains your application's exception handler and is also a good
place to stick any exceptions thrown by your application.
PLAZMA INSTITUTE Page 21
MSC(IT & CA ) SEM 1 LARAVEL
 The Jobs directory, of course, houses the queue table jobs for your application. Jobs may be
queued by your application or run synchronously within the current request lifecycle.
 The Listeners directory contains the handler classes for your events. Handlers receive an
event and perform logic in response to the event being fired. For example, a User Registered
event might be handled by a Send Welcome Email listener.
 The Policies directory contains the authorization policy classes for your application. Policies
are used to determine if a user can perform a given action against a resource.
 For more information check out the authorization documentation.

Q: 10 Explain Artisan Command Line Tool.


 Artisan is the name of the command-line interface included with Laravel. It provides a number of
helpful commands for your use while developing your application.
 It is driven by the powerful Symfony Console component.

Usage

Listing All Available Commands

 To view a list of all available Artisan commands, you may use the list command:
php artisan list

Viewing The Help Screen For A Command

 Every command also includes a "help" screen which displays and describes the command's
available arguments and options.
 To view a help screen, simply precede the name of the command with help:
php artisan help migrate

Writing Commands

 In addition to the commands provided with Artisan, you may also build your own custom
commands for working with your application.
 You may store your custom commands in the app/Console/Commands directory
Php artisan make:console Send Email

Command Structure

 Once your command is generated, you should fill out the signature and description proper-
ties of the class, which will be used when displaying your command on the list screen.
 The handle method will be called when your command is executed. You may place any
command logic in this method.

PLAZMA INSTITUTE Page 22


MSC(IT & CA ) SEM 1 LARAVEL
 Example:

<?php

namespaceApp\Console\Commands;
use App\User;

use App\DripEmailer;

use Illuminate\Console\Command;

class SendEmails extends Command

Protected $signature='email:send{user}';

Protected $description='Send dripe-mailstoauser';

protected $drip;

Public functioncon struct(DripEmailer$drip)

parent::construct();

$this->drip= $drip;

Public function handle()

$this->drip->send(User::find($this->argument('user')));

PLAZMA INSTITUTE Page 23


MSC(IT & CA ) SEM 1 LARAVEL
Q – 11 : Explain Artisan Migration.
Ans : Migration are like version control for your database allowing a team to easily modify and share
the application database schema.

 migration are typically pair with Laravel’s schema builder easily to your application database
schema.
 The Laravel schema provide database support for creating and manipulating table.

1.Generating Migration:

 To create a migration use the make:migration artisan command


: Php artisan make:migration Create_User_Table

 The new migration will be placed in your database/migration directory.


 If you would like to specify a custom output path for the generated migration you may use
the –path option when executing the make:migration command.
 The –table & --create option may also be used to indicate the name of the table and whether
migration will be created a new table.

2.Migration Structure:

 The migration class contain two method.


1 Up()

2 down()

 The up() is used to add new Table Column or Index to your database.
 The down() Should simply reserve the operation by the up() within both of this method you
may use the Laravel schema builder to create and modify tables.

3.Creation Migration:

 To run all outstanding migration for your application use migrate artisan command.
- Php artisan migrate

4.Rolling Back Migration:

 To rollback the latest migration “operation” you may use the rollback command
- Php artisan migrate:rollback

5.Writing Migration:

 Create Table: - To create a new table use the create method on the schema fcode.
 Rename / Drop Table: - To rename an existing database table use the rename method

PLAZMA INSTITUTE Page 24


MSC(IT & CA ) SEM 1 LARAVEL
Q : 12 what is routing? explain in brief.
Ans :// Display a form to create a blog post...

Route::get('post/create', 'Post Controller@create');

 All request are map with the help of routes. Basic routes route the request to the associated
controls.
 Routing in Laravel include the following categories.
1. Basic Routing:
 all Laravel routes are defined in app/HTTP/routs.php file, which is automatically loaded by
framework.
 This file tells Laravel for the URL it should responds to and the associated control will give it a
particular call.
 Example:
route::get (‘/’ function(){
Return view (‘welcome’);
});

 Available Router Methods:


 Route::get($URL,$callback);
 Route::post($URL,$callback);
 Route::put($URL,$callback);
 Route::patch($URL,$callback);
 Route::delete($URL,$callback);
 Route::option($URL,$callback);

2. Route Parameter:
 With intent to capture the parameter pass with URL. - We need to modify the code In
routes.php
Example:
route::get (‘user/{id}’,function (id) {
Return ‘user’,$id);
});

3 .Name Route:

 Name route allow a convince name of creating a rules.


 the chaining of routes can be specify using name method on to the routr definition.
Example:
route::get(‘user/profile’,array(‘as-> ‘profile’,
‘use’ -> ‘userController@showprofile’));

PLAZMA INSTITUTE Page 25


MSC(IT & CA ) SEM 1 LARAVEL
4 .Route Group:
 Sometimes you may need to apply filter to a group or route instead of specifying the filter on
each route you may use a route group.

Route::group (array(‘before’ -> ‘auth’),function(){


Route::get (‘/’,function(){//has auth filter});

Route::get(‘user/profile’,function(){

// has auth filter

});

Q : 13 Explain controllers.
 Instead of defining all of your request handling logic as closures in your route files, you may wish
to organize this behavior using "controller" classes.
 Controllers can group related request handling logic into a single class. For example, a User
Controller class might handle all incoming requests related to users, including showing, creating,
updating, and deleting users.
 By default, controllers are stored in the app/Http/Controllers directory.
 Basic Controllers Let's take a look at an example of a basic controller.

Note: that the controller extends the base controller class included with Laravel:
App\Http\Controllers\Controller:

use App\Http\Controllers\User Controller;

Route::get('/user/{id}',[User Controller::class,'show']);

 You can define a route to this controller method like so:


 Controller Middleware Middleware may be assigned to the controller's routes in your route files:

Route::get('profile',[UserController::class,'show'])->middleware('auth');

 Or, you may find it convenient to specify middleware within your controller's
constructor. Using the middleware method within your controller's constructor, you
can assign middle- ware to the controller's actions:

PLAZMA INSTITUTE Page 26


MSC(IT & CA ) SEM 1 LARAVEL
Class User Controller extends Controller

/**

* Instantiate a new controller instance.


*

* @return void
*/

Public function construct()

$this->middleware('auth');

$this->middleware('log')->only('index');

$this->middleware('subscribed')->except('store');

Q : 14 What is blade template?


 Blade is the simple, yet powerful templating engine that is included with Laravel.
 Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in
your templates.
 In fact, all Blade templates are compiled into plain PHP code and cached until they are
modified, meaning Blade adds essentially zero overhead to your application.
 Blade template files use the .blade.php file extension and are typically stored in the
resources/views directory.
 Blade views may be returned from routes or controllers using the global view helper. Of course,
as mentioned in the documentation on views, data may be passed to the Blade view using the
view helper's second argument:

Route::get('/',function(){

returnview('greeting',['name'=>'Finn']);

});

 Displaying Data
 You may display data that is passed to your Blade views by wrapping the variable in curly
braces. For example, given the following route:

PLAZMA INSTITUTE Page 27


MSC(IT & CA ) SEM 1 LARAVEL
Route::get('/',function(){

returnview('welcome',['name'=>'Samantha']);

});

 Components :
 To create a class based component, you may use the make:component Artisan command. To
illustrate how to use components, we will create a simple Alert component. The
make:component command will place the component in the app/View/Components directory:

Php artisan make:component Alert

 Slots :
 You will often need to pass additional content to your component via "slots". Component slots
are rendered by echoing the $slot variable. To explore this concept, let's imagine that an alert
component has the following markup:
<!--/resources/views/components/alert.blade.php-->

<div class="alertalert-danger">

{{$slot}}

</div>

 Control Structures
 In addition to template inheritance and displaying data, Blade also provides convenient short-
cuts for common PHP control structures, such as conditional statements and loops.
 These short-cuts provide a very clean, terse way of working with PHP control structures, while
also remaining familiar to their PHP counterparts.
 If Statements You may construct if statements using the @if, @elseif, @else, and @endif
directives. These directives function identically to their PHP counterparts:

@if(count($records)===1) I
have one record!

@elseif(count($records)>1) I
have multiple records!

@else

Idon'thaveanyrecords!
@endif

PLAZMA INSTITUTE Page 28


MSC(IT & CA ) SEM 1 LARAVEL
 Loops
 In addition to conditional statements, Blade provides simple directives for working
with PHP's supported loop structures.
 Again,each of the directives function sidentically to their PHP counterparts:

@for ($i = 0; $i < 10; $i++)

The current value is{{$i}}

@end for

 Extending A Layout When defining a child page, you may use the Blade @extends directive to
specify which layout the child page should "inherit".
 Views which @extends a Blade layout may inject content into the layout's sections using
@section directives. Remember, as seen in the example above, the contents of these sections
will be displayed in the layout using @yield:

<!—Stored in resources/views/child.blade.php--

>@extends('layouts.master')

@section('title','PageTitle')

@section('sidebar')
@@parent

<p>This is appended to the master side bar.</p>

@end section

@section('content')

<p>This is my body content.</p>@endsection

 Ofcourse,just like plain PHP views, Blade views may be returned from routes using the
global view helper function:

Route::get('blade',function(){
return view('child');

});

PLAZMA INSTITUTE Page 29


MSC(IT & CA ) SEM 1 LARAVEL
 Including Subviews
 Blade's @include directive allows you to include a Blade view from within another
view. All variables that are available to the parent view will be made available to
the included view:

<div>

@include('shared.errors')

<form>

<!--FormContents-->

</form>

</div>
 Stacks :
 Blade allows you to push to named stacks which can be rendered somewhere else in
another view or layout. This can be particularly useful for specifying any JavaScript
libraries required by your child views:

@push('scripts')

<script src="/example.js">

</script>@endpush

 Service Injection :
 The @inject directive may be used to retrieve a service from the Laravel service container. The
first argument passed to @inject is the name of the variable the service will be placed into,
while the second argument is the class or interface name of the service you wish to resolve:

@inject('metrics','App\Services\Metrics Service')

<div>

Monthly Revenue:{{$metrics->monthly Revenue()}}.

</div>

 Extending Blade :

 Blade allows you to define your own custom directives using the directive method. When the
Blade compiler encounters the custom directive, it will call the provided callback with the
expression that the directive contains.

PLAZMA INSTITUTE Page 30


MSC(IT & CA ) SEM 1 LARAVEL

Q : 15 Explain Forms in Laravel.


 Ans: Installation Begin by installing this package through Composer. Edit your project's
composer.json file to require Laravel collective/html.

$ composer require Laravel collective/html

 Looking to install this package in Lumen? First of all, making this package compatible with Lumen
will require some core changes to Lumen, which we believe would dampen the effectiveness of
having Lumen in the first place. Secondly, it is our belief that if you need this package in your
application, then you should be using Laravel anyway

 Opening a form :

{!! Form::open(['url' => 'foo/bar']) !!}

//

{!! Form::close() !!}

 By default, a POST method will be assumed; however, you are free to specify
another method:
echo Form::open(['url' => 'foo/bar', 'method' => 'put'])

 Labels
 Generating A Label
echo Form::label('email', 'E-Mail Address');
Element Specifying Extra
HTML Attributes
echo Form::label('email', 'E-Mail Address', ['class' => 'awesome']);

Note: After creating a label, any form element you create with a name matching the
label name will automatically receive an ID matching the label name as well.

Generating A Text Input

echo Form::text('username');

Specifying A Default Value


echo Form::text('email', '[email protected]');
Note: The hidden and textarea methods have the same signature as the text method.
PLAZMA INSTITUTE Page 31
MSC(IT & CA ) SEM 1 LARAVEL

Generating A Password

echo Form::password('password', ['class' => 'awesome']);


Input Generating Other input

echo Form::email($name, $value = null, $attributes = []);


echo Form::file($name, $attributes = []);

Checkboxes and Radio Buttons


Generating A Checkbox Or Radio Input
echo Form::checkbox('name', 'value');

echo Form::radio('name', 'value');

Generating A Checkbox Or Radio Input That Is Checked


echo Form::checkbox('name', 'value', true);

echo Form::radio('name', 'value', true);

Number
Generating A Number Input
echo Form::number('name', 'value');

Date
Generating A Date Input
echo Form::date('name', \Carbon\Carbon::now());

File Input
Generating A File Input
echo Form::file('image');

Note: The form must have been opened with the files option set to true.

Drop-Down Lists
Generating A Drop-Down List
echo Form::select('size', ['L' => 'Large', 'S' => 'Small']);

Generating A Drop-Down List With Selected Default

echo Form::select('size', ['L' => 'Large', 'S' => 'Small'], 'S');

Generating a Drop-Down List With an Empty Placeholder.

PLAZMA INSTITUTE Page 32


MSC(IT & CA ) SEM 1 LARAVEL
 This will create an <option> element with no value as the very first option
ofyour drop- down.
echo Form::select('size', ['L' => 'Large', 'S' => 'Small'], null, ['placeholder' => 'Pick a size...']);
Generating A Grouped List
echo Form::select('animal',[

'Cats' => ['leopard' =>


'Leopard'],'Dogs' =>
['spaniel' =>
'Spaniel'],

]);

Generating A Drop-Down List With A


Range

echo Form::selectRange('number', 10, 20);

Generating A List With Month names:


echo Form::selectMonth('month');

Buttons
Generating a submit button
echo Form::submit('Click Me!');
Note: Need to create a button element? Try the button method. It has the same
signature as submit.

Q: 16 Explain Custom Macros And CSRF Token.


Ans :Custom Macros

 Registering A Form Macro


 It's easy to define your own custom Form class helpers called "macros".
Here's how it works.
First, simply register the macro with a given name and a Closure

Form::macro('myField', function()

return '<input type="awesome">';

});
Now you can call your macro using its

name: Calling A Custom Form Macro


echo Form::myField();

PLAZMA INSTITUTE Page 33


MSC(IT & CA ) SEM 1 LARAVEL
CSRF Protection
 Adding The CSRF Token To A Form
 Laravel provides an easy method of protecting your application from cross-
site request forgeries.
 First, a random token is placed in your user's session.
 If you use the Form::open method with POST, PUT or DELETE the CSRF token
will be added to your forms as a hidden field automatically.
 Alternatively, if you wish to generate the HTML for the hidden CSRF field,
 you may use the token method:
echo Form::token();

 Attaching The CSRF Filter To A Route


Route::post
('profile',[

'before'
=>
'csrf',
functio
n()

//

);

Q 17 :Explain validation.
Ans:

 Defining The Routes


// Display a form to create a blog post...
Route::get('post/create', 'Post Controller @create');

// Store a new blog post...


Route::post('post', 'Post Controller@store');

 Of course, the GET route will display a form for the user to create a new blog post,
while the POST route will store the new blog post in the database.

 Creating The Controller :


 Next, let's take a look at a simple controller that handles these routes.
 We'll leave the store method empty for now:

PLAZMA INSTITUTE Page 34


MSC(IT & CA ) SEM 1 LARAVEL

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

class Post Controller extends Controller

public function create()

return view('post.create');

public function store(Request $request)

// Validate and store the blog post...

 Writing the Validation Logic :


 The validate method accepts an incoming HTTP request and a set of validation rules.
 If the validation rules pass, your code will keep executing normally; however, if
validation fails, an exception will be thrown and the proper error response will
automatically be sent back to the user.
 In the case of a traditional HTTP request, a redirect response will be generated,
while a JSON response will be sent for AJAX requests.
public function store(Request $request)
{
$this->validate($request, [
'title' =>
'required|unique:posts|max:25
5','body' => 'required',
]);

// The blog post is valid, store in database...


}

PLAZMA INSTITUTE Page 35


MSC(IT & CA ) SEM 1 LARAVEL
 Displaying The Validation Errors
 we did not have to explicitly bind the error messages to the view in our GET route.
 This is because Laravel will check for errors in the session data, and
automatically bind them to the view if they are available.
 The $errors variable will be an instance of Illuminate\Support\Message Bag.
 The $errors variable is bound to the view by the
Illuminate\View\Middleware\Share Errors From Session middleware, which
isprovided by the web middleware group.

 Validating Arrays
 Validating array form input fields doesn't have to be a pain.
 For example, to validate that each e-mail in a given array input field is unique, you
may dothe following:
$validator = Validator::make($request->all(),

['person.*.email' => 'email|unique:users',

'person.*.first_name' => 'required_with:person.*.last_name',

]);

Q : 18 Explain Available Validators.

1. Accepted
 The field under validation must be yes, on, 1, or true.
 This is useful for validating "Terms of Service" acceptance.
2. After: date
 The field under validation must be a value after a given date. The dates will be passed
into the str to time PHP function:
'start_date' => 'required|date|after:tomorrow'

 Instead of passing a date string to be evaluated by strtotime, you may specify another
field to compare against the date:
'finish_date' => 'required|date|after:start_date'
3. alpha
 The field under validation must be entirely alphabetic characters.

4. alpha_dash
 The field under validation may have alpha-numeric characters, as well as dashesand
underscores.
5. alpha_num
 The field under validation must be entirely alpha-numeric characters.

PLAZMA INSTITUTE Page 36


MSC(IT & CA ) SEM 1 LARAVEL

6. array
 The field under validation must be a PHP array.

7. before: date
 The field under validation must be a value preceding the given date
 .The dates will be passed into the PHP strtotime function.

8. Between :min, max


 The field under validation must have a size between the given min and max.
 Strings, numerics, and files are evaluated in the same fashion as the size rule.

9. boolean
 The field under validation must be able to be cast as a boolean.
 Accepted input are true, false, 1, 0, "1", and "0".
10. date
 The field under validation must be a valid date according to the strtotime
php function.

11. date_format:format
 The field under validation must match the given format.
 The format will be evaluated using the PHP date_parse_from_format function.
You should use either date or date_format when validating a field, not both.

12. different:field
 The field under validation must have a different value than field.

13. digits:value
 The field under validation must be numeric and must have an exact length of value.

14. digits_between:min,max
 The field under validation must have a length between the given min and max.

15. email
 The field under validation must be formatted as an e-mail address.

16. exists:table,column
 The field under validation must exist on a given database table.
'state' => 'exists:states'
17. File (Image)
 The field under validation must be a Image (.jpeg, .gif, .png or .svg)

18. in:foo,bar,...
 The field under validation must be included in the given list of values.

19. integer
 The field under validation must be an integer.

PLAZMA INSTITUTE Page 37


MSC(IT & CA ) SEM 1 LARAVEL

20. max:value
 The field under validation must be less than or equal to a maximum value.
 Strings, numerics, and files are evaluated in the same fashion as the size rule

21. min:value
 The field under validation must have a minimum value.
 Strings, numerics, and files are evaluated in the same fashion as the size rule.

22. not_in:foo,bar,...
 The field under validation must not be included in the given list of values.
23. numeric
 The field under validation must be numeric.

24. regex:pattern
 The field under validation must match the given regular expression.

Q : 19 Explain Migration in Laravel.

Ans:

 Migration are like version control for your database allowing a team to easily
modify andshare the application database schema.
 Migration are typically pair with Laravel’s schema builder to easily your application
databaseschema.
 The Laravel schema facade provide database support for creating and manipulating.
 Generating Migrations

 To create a migration, use the make:migration Artisan command:


php artisan make:migration create_users_table
 The new migration will be placed in your database/migrations directory.
 If you would like to specify a custom output path for the generated migration, you
may usethe --path option when executing the make:migration command.
 The provided path should be relative to your application's base path.

 The --table and --create options may also be used to indicate the name of the
table and whether the migration will be creating a new table.
 These options simply pre-fill the generated migration stub file with the specified
table:
php artisan make:migration add_votes_to_users_table --table=users
php artisan make:migration create_users_table --create=users

PLAZMA INSTITUTE Page 38


MSC(IT & CA ) SEM 1 LARAVEL

 Migration Structure
 A migration class contains two methods: up and down.
 The up method is used to add new tables, columns, or indexes to your database
 The down method should simply reverse the operations performed by the up
method.
 Within both of these methods you may use the Laravel schema builder to
expressively create and modify tables.
 To learn about all of the methods available on the Schema builder, check out its
documentation.
 For example, let's look at a sample migration that creates a flights table:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFlightsTable extends Migration{

public function up() {

Schema::create('flights', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('airline');

$table->timestamps();

});

public function down() {

Schema::drop('flights');

PLAZMA INSTITUTE Page 39


MSC(IT & CA ) SEM 1 LARAVEL
 Creation Migration
 To run all outstanding migrations for your application, use migrate Artisan
command.
 If you are using the Homestead virtual machine, you should run this command from
within your VM:
php artisan migrate

 If you receive a "class not found" error when running migrations, try running the
composer dump-autoload command and re-issuing the migrate command.

 Rolling Back Migrations

 To rollback the latest migration "operation", you may use the rollback command.

Note : that this rolls back the last "batch" of migrations that ran, which may
includemultiple migration files:
php artisan migrate:rollback
 Writing Migration:
 Create Table:
- To create a new table, use the create method on the schema facade.
Schema::create('users', function (Blueprint $table) {

$table->increments('id');

});

 Rename / Drop Table:


- to rename an existing database table use the rename method.
Schema::rename($from, $to);

- to drop an existing table, use this method


Schema::drop('users');

Schema::dropIfExists('user’)

Q : 20 Explain Running Raw SQL.

Ans:

 Once you have configured your database connection, you may run queries using the DB
facade.
 The DB facade provides methods for each type of query: select, update, insert,
delete, and statement.
PLAZMA INSTITUTE Page 40
MSC(IT & CA ) SEM 1 LARAVEL
1. Running A Select Query
 To run a basic query, we can use the select method on the DB facade:
<?php

namespace App\Http\Controllers;

use DB;

use App\Http\Controllers\Controller;

class UserController extends Controller

public function index()

$users = DB::select('select * from users where active = ?', [1]);


return view('user.index', ['users' => $users]);

2. Running An Insert Statement:


 To execute an insert statement, you may use the insert method on the DB façade.
 Like select, this method takes the raw SQL query as its first argument, and
bindings as thesecond argument:

DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);

3. Running An Update Statement


 The update method should be used to update existing records in the database.
 The number of rows affected by the statement will be returned by the method:

$affected = DB::update('update users set votes = 100 where name = ?', ['John']);

4.Running A Delete Statement


 The delete method should be used to delete records from the database.
 Like update, the number of rows deleted will be returned:

PLAZMA INSTITUTE Page 41


MSC(IT & CA ) SEM 1 LARAVEL

$deleted = DB::delete('delete from users');

5. Running A General Statement


 Some database statements should not return any value.
 For these types of operations, you may use the statement method on the DB facade:

DB::statement('drop table users');

Q : 21 Explain running raw SQL queries.


Ans :

 Once you have configured your database connection, you may run queries using the DB facade. The
DB facade provides methods for each type of query: select, update, insert, delete, and statement.

 Running A Select Query


 To run a basic query, we can use the select method on the DB facade:

<?php

namespace App\Http\Controllers;

use DB;

use App\Http\Controllers\Controller;

class User Controller extends Controller

Public unctionindex()

$users=DB::select('select*fromuserswhereactive=?',[1]); return
view('user.index', ['users' => $users]);

PLAZMA INSTITUTE Page 42


MSC(IT & CA ) SEM 1 LARAVEL

 Running An Insert Statement


 To execute an insert statement, you may use the insert method on the DB facade. Like select,
this method takes the raw SQL query as its first argument, and bindings as the second argument

DB::insert('insert in to users(id,name)values(?,?)',[1,'Dayle']);

 Running An Update Statement


 The update method should be used to update existing records in the database. The number of
rows affected by the statement will be returned by the method.

$affected=DB::update('update users set votes=100wherename=?', ['John']);

 Running A Delete Statement


 The delete method should be used to delete records from the database. Like update, the
number of rows deleted will be returned:

$deleted=DB::delete('delete from users');

 Running A General Statement


 Some database statements should not return any value. For these types of operations, you
may use the statement method on the DB facade:

DB::statement('drop table users');

Q : 22 Explain query builder.


 The database query builder provides a convenient, fluent interface to creating and running
database queries.
 It can be used to perform most database operations in your application, and works on all
supported database systems.

Note: The Laravel query builder uses PDO parameter binding to protect your application against
SQL injection attacks. There is no need to clean strings being passed as bindings.

PLAZMA INSTITUTE Page 43


MSC(IT & CA ) SEM 1 LARAVEL
 Retrieving Results
 Retrieving All Rows From A Table To begin a fluent query, use the table method on the DB facade.
 The table method returns a fluent query builder instance for the given table, allowing you to chain
more constraints onto the query and then finally get the results. In this example, let's just get all
records from a table:

<?php

Name spaceApp\Http\Controllers;

use DB;

use App\Http\Controllers\Controller;

class User Controller extends Controller

Public function index()

$users=DB::table('users')->get();

 Chunking Results From A Table


 If you need to work with thousands of database records, consider using the chunk method.
returnview('user.index',['users'=>$users]);
 This method retrieves a small "chunk" of the results at a time, and feeds each chunk into a
Closure for processing.
}
 This method is very useful for writing Artisan commands that process thousands of records.
}

DB::table('users')->order By('id')->chunk(100,function($users){
foreach ($users as $user) {

//

});

PLAZMA INSTITUTE Page 44


MSC(IT & CA ) SEM 1 LARAVEL

 Aggregates
 The query builder also provides a variety of aggregate methods, such as count, max, min, avg,
and sum.
 You may call any of these methods after constructing your query:
$users=DB::table('users')->count();

$price=DB::table('orders')->max('price');

 Specifying A Select Clause


 Of course, you may not always want to select all columns from a database table.
 Using the select method, you can specify a custom select clause for the query:

$users=DB::table('users')->select('name','emailasuser_email')->get();

 Raw Expressions
 Sometimes you may need to use a raw expression in a query.
 These expressions will be injected into the query as strings, so be careful not to create any
SQL injection points!
 To create a raw expression, you may use the DB::raw method:

$users=DB::table('users')

->select(DB::raw('count(*)asuser_count,status'))

->where('status','<>',1)

->groupBy('status')

->get();

Q : 23 EXPLAIN JOIN.
 Inner join statement :
 The query builder may also be used to write join statements.
 To perform a basic SQL "inner join", you may use the join method on a query builder instance.
The first argument passed to the join method is the name of the table you need to join to,
while the remaining arguments specify the column constraints the join.

PLAZMA INSTITUTE Page 45


MSC(IT & CA ) SEM 1 LARAVEL
 Of course, as you can see, you can join to multiple tables in a single query:

 Left join statement :


 If you would like to perform a "left join" instead of an "inner join", use the left Join method.
The left Join method has the same signature as the join method:

$users=DB::table('users')

->left Join('posts','users.id','=','posts.user_id')

->get();

 Cross Join Statement


 To perform a "cross join" use the cross Join method with the name of the table you wish to
cross join to.
 Cross joins generate a cartesian product between the first table and the joined table:

$users=DB::table('sizes')

->cross Join('colours')

->get();

 Advance join statement :


 You may also specify more advanced join clauses. To get started, pass a Closure as the second
argument into the join method.
 The Closure will receive a Join Clause object which allows you to specify constraints on the
join clause:

DB::table('users')

->join('contacts',function($join) {

$join->on('users.id','=','contacts.user_id')->orOn(...);

})

->get();

PLAZMA INSTITUTE Page 46


MSC(IT & CA ) SEM 1 LARAVEL
Q : 24 Explain defining models.
 To get started, let's create an Eloquent model. Models typically live in the app directory, but you
are free to place them anywhere that can be auto-loaded according to your composer.json file.
 All Eloquent models extend Illuminate\Database\Eloquent\Model class. The easiest way to create
a model instance is using the make:model Artisan command:

Php artisan make:model User

 If you would like to generate a database migration when you generate the model, you may use the
--migration or -m option:

Php artisan make:model User--migration

Php artisan make:modelUser-m

 Table Names
 Note that we did not tell Eloquent which table to use for our Flight model.

<?php

namespaceApp;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model

Protected $table='my_flights';

 Primary Keys
 Eloquent will also assume that each table has a primary key column named id.
 You may define a $primary Key property to override this convention.

 Timestamps
 By default, Eloquent expects created_at and updated_at columns to exist on your tables.
 If you do not wish to have these columns automatically managed by Eloquent, set the
$timestamps property on your model to false:

PLAZMA INSTITUTE Page 47


MSC(IT & CA ) SEM 1 LARAVEL

Q : 25 Explain model relationship.


 Database tables are often related to one another. For example, a blog post may have many
comments, or an order could be related to the user who placed it.
 Eloquent makes managing and working with these relationships easy, and supports several
different types of relationships:

1. One To One One


2. To Many Many
3. To Many Has Many Through
4. Defining Relationships
5. Eloquent relationships are defined as functions on your Eloquent model classes

1. One to one :
 A one-to-one relationship is a very basic relation. For example, a User model might be
associated with one Phone. To define this relationship, we place a phone method on the User
model.
 The phone method should return the results of the has One method on the base Eloquent
model class:

<?php

Name space App;

use Illuminate\Database\Eloquent\Model;

class User extends Model

Public function phone()

Return $this->has One('App\Phone');

2. One to many :
 One To Many A "one-to-many" relationship is used to define relationships where a single model
owns any amount of other models. For example, a blog post may have an infinite number of
comments.
 Like all other Eloquent relationships, one-to-many relationships are defined by placing a
function on your Eloquent model:

PLAZMA INSTITUTE Page 48


MSC(IT & CA ) SEM 1 LARAVEL

<?php

namespaceApp;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

/**

*Get the comments for the blog post.

*/

Public function comments()

Return $this->has Many('App\Comment');

3. Many To Many
 Many-to-many relations are slightly more complicated than has One and has Many relationships.
 An example of such a relationship is a user with many roles, where the roles are also shared by
other users.
 Many-to-many relationships are defined by writing a method that calls the belongs To Many
method on the base Eloquent class.
4. Collection :
 collections All multi-result sets returned by Eloquent are instances of the
Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or
accessed via a relationship.
 The Eloquent collection object extends the Laravel base collection, so it naturally inherits dozens
of methods used to fluently work with the underlying array of Eloquent models.
 Of course, all collections also serve as iterators, allowing you to loop over them as if they were
simple PHP arrays:

$users=App\User::where('active',1)->get();

For each($users as $user){


echo $user->name;

PLAZMA INSTITUTE Page 49


Q : 26 Explain API resources introduction.

 When building an API, you may need a transformation layer that sits between your Eloquent
models and the JSON responses that are actually returned to your application's users.
 Laravel's resource classes allow you to expressively and easily transform your models and model
collections into JSON.
 Generating Resources 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:

Php artisan make:resource User

 Resource Collections :
 In addition to generating resources that transform individual models, you may generate resources
that are responsible for transforming collections of models.
 This allows your response to include links and other meta information that is relevant to an entire
collection of a given resource.
 To create a resource collection, you should use the --collection flag when creating the resource.
Or, including the word Collection in the resource name will indicate to Laravel that it should create
a collection resource.
 Collection resources extend the Illuminate\Http\Resources\Json\Resource Collection class:

Php artisan make:resourceUsers--collection

Php artisan make:resource User Collection

 Writing Resources :

 In essence, resources are simple.


 They only need to transform a given model into an array.
 So, each resource contains a to Array method which translates your model's attributes into an
API friendly array that can be returned to your users:
<?php

Name space App\Http\Resources;

useIlluminate\Http\Resources\Json\Json Resource;

class User extends Json Resource

/**

* Transform the resource in to an array.


*

* @param\Illuminate\Http\Request $request
* @return array

Q : 27 Explain passport tokens.


 Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a
matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by
Andy Millington and Simon Hamp.

 Installation :
 To get started, install Passport via the Composer package manager:

Composer require laravel/passport

 Passport's service provider registers its own database migration directory, soyou should
migrate your database after installing the package.

 The Passport migrations will create the tables your application needs to store OAuth2
clients and access tokens:

php artisan migrate


 Next, you should execute the passport :install Artisan command.

 This command will create the encryption keys needed to generate secure
access tokens.

 In addition, the command will create "personal access" and "password grant"
clients which will be used to generate access tokens:

php artisan passport:install

You might also like