Laravel New
Laravel New
PREPARED BY:
PREPARED BY:
PRO.PRASHIL MAHETA
BY :PLAZMA INSTITUTE
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.
• PHP is faster than other scripting languages, for example, ASP and JSP.
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.
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.
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.
<?php
Class My Class{
}
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{
Echo self::geet;
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();
?>
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.
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.
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:
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:
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.
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 )
__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 .
__debugInfo()
array __debugInfo ( void ) This method is called by var_dump() when dumping an object to
get the properties that should be shown.
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.
<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
<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.
<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:
<html>
<head>
<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.
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.
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.
<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.
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.
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
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.
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.
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.
Q 7 : Installation of Laravel.
Using the installer:
1. This is the easiest way to get composer set up on your machine.
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.
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.
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.
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.
Usage
To view a list of all available Artisan commands, you may use the list command:
php artisan list
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.
<?php
namespaceApp\Console\Commands;
use App\User;
use App\DripEmailer;
use Illuminate\Console\Command;
Protected $signature='email:send{user}';
protected $drip;
parent::construct();
$this->drip= $drip;
$this->drip->send(User::find($this->argument('user')));
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:
2.Migration Structure:
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
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
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’);
});
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:
Route::get(‘user/profile’,function(){
});
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:
Route::get('/user/{id}',[User Controller::class,'show']);
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:
/**
* @return void
*/
$this->middleware('auth');
$this->middleware('log')->only('index');
$this->middleware('subscribed')->except('store');
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:
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:
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
@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
@end section
@section('content')
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');
});
<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>
</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.
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 :
//
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.
echo Form::text('username');
Generating A Password
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']);
]);
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.
Form::macro('myField', function()
});
Now you can call your macro using its
'before'
=>
'csrf',
functio
n()
//
);
Q 17 :Explain validation.
Ans:
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.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
return view('post.create');
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(),
]);
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.
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.
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.
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.
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
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
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{
$table->increments('id');
$table->string('name');
$table->string('airline');
$table->timestamps();
});
Schema::drop('flights');
If you receive a "class not found" error when running migrations, try running the
composer dump-autoload command and re-issuing the migrate command.
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');
});
Schema::dropIfExists('user’)
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;
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
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.
<?php
namespace App\Http\Controllers;
use DB;
use App\Http\Controllers\Controller;
Public unctionindex()
$users=DB::select('select*fromuserswhereactive=?',[1]); return
view('user.index', ['users' => $users]);
DB::insert('insert in to users(id,name)values(?,?)',[1,'Dayle']);
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.
<?php
Name spaceApp\Http\Controllers;
use DB;
use App\Http\Controllers\Controller;
$users=DB::table('users')->get();
DB::table('users')->order By('id')->chunk(100,function($users){
foreach ($users as $user) {
//
});
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');
$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.
$users=DB::table('users')
->left Join('posts','users.id','=','posts.user_id')
->get();
$users=DB::table('sizes')
->cross Join('colours')
->get();
DB::table('users')
->join('contacts',function($join) {
$join->on('users.id','=','contacts.user_id')->orOn(...);
})
->get();
If you would like to generate a database migration when you generate the model, you may use the
--migration or -m option:
Table Names
Note that we did not tell Eloquent which table to use for our Flight model.
<?php
namespaceApp;
use Illuminate\Database\Eloquent\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:
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
use Illuminate\Database\Eloquent\Model;
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:
<?php
namespaceApp;
use Illuminate\Database\Eloquent\Model;
/**
*/
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();
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:
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:
Writing Resources :
useIlluminate\Http\Resources\Json\Json Resource;
/**
* @param\Illuminate\Http\Request $request
* @return array
Installation :
To get started, install Passport via the Composer package manager:
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:
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: