LARAVEL REVISION

 


1) What is Laravel?

Laravel is an open source PHP framework. It is used to design and develop web applications. It is based on MVC (Model-View-Controller) design pattern. It is created by Taylor Otwell in June 2011.


2) What are Advantages of Laravel?

There are various advantages of Laravel:

  • Easy and consistent syntax
  • Set-up process is easy
  • customization process is easy
  • code is always regimented with Laravel


3) What are the feature of Laravel5.0?

Laravel has following features :

  • Method injection
  • Contracts
  • Route caching
  • Events object
  • Multiple file system
  • Authentication Scaffolding
  • dotenv - Environmental Detection
  • Laravel Scheduler


4) Compare Laravel with Codeigniter?

LaravelCodeigniter
It is a framework with expressive, elegant syntax.It is a powerful PHP framework
Development is enjoyable, creative experienceIt provides simple toolkit to create full-featured web applications.
Laravel is built for latest version of PHPCodeigniter is an older more mature framework
It is more object oriented compared to CodeIgniter.It is less object oriented compared to Laravel.
Laravel community is still small, but it is growing very fastCodeigniter community is large.


5) How we can set database connection in Laravel?

In Laravel, we can set database connection into .env file. It is stored into project folder.


6) What are Bundles, Reverse Routing and The IoC container in Laravel?

Bundles: These are small functionalities which we can download to add in our web application. Reverse Routing: It allows to change routes and application and also update all of the relevant links as per this link. IoC container: It gives us control and a method for generating new objects and optionally instantiating and referencing singletons.


7) How can we create enable Query Logging?

We can create enable login query through the following command:

DB::connection()->enableQueryLog();

8) What is Composer in laravel ?

In Laravel, composer is a dependency manager for PHP. It manage all the dependencies you require on a project by project basis. This means, it will pull in all the required libraries, dependencies and manage them all in one place.

In PHP, Laravel is a powerful framework where composer is a dependency manager, It manages all the dependencies that are required in the project. Composer automatically fetch required dependencies, libraries and manage them in our project.


9) What is Lumen in Laravel?

In Laravel, Lumen is a new project from Laravel creator Taylor Otwell. Lumen is a micro-framework. PHP has two other popular micro-frameworks:

  • Slim
  • Silex.


10) How do we implement our own package in Laravel?

We can implement own package in laravel using the following steps:

  • Package folder and name
  • Composer.json file for the package
  • Loading package via main composer.json and PSR-4
  • Creating a Service Provider
  • Create a Controller for your package
  • Create our Routes.php file


11) What are the official packages provided by Laravel?

Laravel provides following official packages.

  • Cashier
  • Envoy
  • Passport
  • Scout
  • Socialite


12) How can we install Laravel via composer ?

We can install Laravel via composer using given command:

composer create-project laravel/laravel example-app

Or, you may create new Laravel projects by globally installing the Laravel installer via Composer:

composer global require laravel/installer
 
laravel new example-app


13) What is php artisan. List out some artisan commands?

PHP artisan is the command line interface or tool included with Laravel. It provides various types of commands that can help us, while we build our application easily. Here are some artisan command:

  • php artisan list
  • php artisan help
  • php artisan tinker
  • php artisan make
  • php artisan make:modal modal_name
  • php artisan make:controller controller_name


14) How can we check current installed version of Laravel?

We can check current installed versions of Laravel using php artisan --version command.

php artisan --version


15) What are the methods provided by query builder in Laravel?

There are various methods provided by query builder in Laravel that are:

1) max()
$price = DB::table('orders')->max('price');
2)count()
$products = DB::table('products')->count();
3)min()
$price = DB::table('orders')->min('price');
4)avg()
$price = DB::table('orders')->avg('price');
5)sum()
$price = DB::table('orders')->sum('price');


15) What is an event in Laravel?

In Laravel, an event is an event or occurrence detected and handled by program. Examples:

  • A new user has registered
  • A new comment is posted
  • User login/logout
  • New product is added.


16) What happen when we type "php artisan" in the command line?

Multiple command option will be appear.


17) Which template engine use Laravel?

Laravel use blade template engine.


18) What are the default databases in Laravel?

MySQL is the default database in Laravel.


19) How can we register a service provide?

We can register a service provide by using following step:

  • Open to config/app.php
  • Find providers array if the various service provider.
  • Add namespace 'Iluminate\Abc\ABCServiceProvider:: class,' to the end of the array


20) What is the use of implicit controllers?

An implicit controller is used to define a single route to handle every action in the controller. Example:

Route::controller('base URI','');


21) What is the use of "composer dump -autoloader in Laravel"?

Composer dump-autoloader is used to reads the composer.json file.


22) How can we get IP address in Laravel?

In Laravel, we can get IP address by using ip() method. Example

public function getUserIp(Request $request){  

// Getting ip address of remote user  

return $user_ip_address=$request->ip();  

}


23) What are the types of relationship supported by Laravel?

There are seven types of relationship supported by Laravel that are given below:

  • One To One
  • One To Many
  • One To Many (Inverse)
  • Many To Many
  • Has Many Through
  • Polymorphic Relations
  • Many To Many Polymorphic Relations


24) What is Laravel Query builder?

Laravel Query builder provide an interface to create and organize database queries.


25) What is Laravel Elixir?

Laravel Elixir provides API for define basic gulp tasks of Laravel application.


26) How can we enable maintenance model in Laravel 5?

We can enable maintenance model in Laravel by using given cod

 //To enable maintenance mode  

php artisan down  

//To disable maintenance mode  

       php artisan up


27) Can Laravel be hacked?

No, Laravel can be hacked. It has inbuilt CSRF security.


28) Doesn't Laravel support PHP7?

Yes, PHP7 supports Laravel.


29) What is a trait in Laravel?

In Laravel, a traits is a group of method that we can include within another class. It is created to reduce the limitations of single inheritance.


30) How to create migration via artisan?

The given below command is used to create migration via artisan.

  1. // creating Migration
    php artisan make:migration create_users_table


31) What is ORM in Laravel?

In Laravel, ORM stands for Object Relation Mapping. It is a programming technique for converting data between incompatible type systems in opps.


32) How to get logged in user info in Laravel?

Auth::User() function is used to get logged in user in Laravel.


------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------



 Name aggregates methods of query builder

1. max()

2. min()

3. sum()

4. avg()

5. count()

=> all


What is Controller?

1. A controller is the "C" in the "MVC" architecture

2. Central unit in MVC

3. Connect model and view

4. Router calls controller directly



Latest version and It's features

As Laravel 8:

1. Laravel Jetstream

2. Models Directory

3. Improved Rate Limiting

4. Improved Maintenance Mode

5. Dynamic Blade Components



WHAT IS PHP ARTISAN?

Php artisan is the command line interface/tool included with laravel. It provides a number of helpful commands that can help you while you build your application easily.



WHAT IS DATA MIGRATION IN LARAVEL

Migrations are like version control for your database, which allows your team to easily modify and share the application's database schema. In laravel db also structured is controlled by Laravel.


WHAT ARE LARAVEL ELOQUENT?

Laravel's Eloquent ORM is simple Active Record implementation for working with your database. Laravel provide many different ways to interact with your database, Eloquent is most notable of them.


WHAT IS QUERY LOG?

Provide the SQL query that is applied by laravel function when we want to perform some operations with database

ex:

dd(DB::getQueryLog());



CAN WE TURN OFF CRSF TOKEN ?

yes, We can

app/Http/Kernel.php

and disable VerifyCsrfToken Middleware



ROUTING METHOD IN LARAVEL

Route::get($uri, $callback);

Route::post($uri, $callback);

Route::put($uri, $callback);

Route::patch($uri, $callback);

Route::delete($uri, $callback);

Route::options($uri, $callback);

Route::any($uri, $callback);

Route::metch($uri, $callback);

Route::view($uri, $callback);


URI: Uniform Resource Identifier



DEFINE LUMEN

Lumen is a micro-framework. It is a smaller, and faster, version of a building laravel based services, and REST API's.



WHAT IS DUMP AND DIE METHOD

Use for Print the result such as print_r

but this is little bit advance to print_r

ex: dd()



WHAT IS LARAVEL API RATE LIMIT

Provide the limit for HTTP request for load controller and secure website.



WHAT IS DEFAULT SESSION TIMEOUT DURATION?

120 MINUTES



ENCRYPTION AND DECRYPTION PASSWORD

We can do it with hashing Class in laravel 

E.g    Hash::make('password')



WHAT IS HTTP MIDDLEWARE

For filter out requested and check the authentication of users such as user is logged in or not.



WHAT ARE ACCESSOR AND MUTATOR IN LARAVEL?

Mutator allows you to alter data before it's saved to database.

Accessor allows you to alter data after it's fetched from a database.



LIST TYPES OF RELATIONSHIPS AVAILABLE IN LARAVEL ELOQUENT?

* ONE TO ONE

* ONE TO MANY

* ONE TO MANY(INVERSE)

* MANY TO MANY

* HAS MANY THROUGH

* POLYMORPHIC RELATIONS



PHP:

Designed byRasmus Lerdorf
DeveloperThe PHP Development Team, Zend TechnologiesPHP Foundation
First appearedJune 8, 1995; 27 years ago



What is the use of .env file in Laravel?

Setting Up local Environment variable



Command to start Laravel Application?

php artisan serve



Command to install laravel project?

composer create-project laravel/laravel myproject



By default laravel project runs on which PORT?

8000



CLI Command to migrate in Laravel project?

php artisan migrate



Command to get the route list in Laravel?

php artisan route:list



CLI Command to create controller in laravel?

php artisan make:controller Mycontroller



Command to make migration in laravel?

php artisan make:migration create_tags_table



Command to check the status of migration in laravel application?

php artisan migrate:status



Command to roll back migration operation in laravel?

php artisan migrate:rollback



Command to rollback all migrations operations?

php artisan migrate:reset



In which file we can set database connections?

.env file


Can laravel application support caching?

Yes



Command to check the current version of the Laravel Framwork?

php artisan --version 



What are the ways to get the data from database in laravel?

Query Builder

Eloquent ORM



Full form of ORM in laravel?

Object Relation Mapping



Laravel is based on which design pattern?

MVC(Model View Controller) Pattern



Which command is used to clear the cache in laravel?

php artisan cache:clear



In which folder .htaccess file is located in laravel?

Public



In which directory robots.txt file is located?

Public



Which command is used to cache configuration in laravel?

php artisan config:cache



Command to enable maintenance mode in laravel?

php artisan down



Command to Disable Maintenance Mode in laravel?

php artisan up



The vendor directory contains in laravel?

Composer dependencies



Method to determine if the user is authenticated?

Auth::check()



Method to logout authenticated user in laravel?

Auth::logout();



Method to logout authenticated user from other devices in laravel?

Auth::logoutOtherDevices($currentPassword);


Bootstrap directory in Laravel is used to

Initialize a Laraval application



Which artisan command is used to remove the compiled class file.

clear-compiled



Which method breaks the collection into multiple, smaller collections of a given size

    chunk()


Artisan command to flush the application cache:

    cache:clear



The vendor directory contains

    Third-party code



Which of following command is used to create a symbolic link from "public/storage" directory to "storage/app/public".

    storage:link



What is the HTTP Status Code for your website. When it is down for maintenance.

    503



__() in laravel used for

    For string translation



What is the minimum PHP version required to install Laravel 5.3?

    5.6.4



Which of the following function in Laravel checks that the desired table is exists in the database or not?

    hasTable()



How to get current action name in Laravel?

    request()->route()->getActionMethod()



ORM: object-relational Mapping



Composer is a tool for ______ in PHP.

    Dependency management



Which class is used in Laravel to handle exceptions?

    App\Exceptions\Handler



When was Laravel first released?

    June 2011



After running “artisan down”, The project will show the maintenance page. What would be HTTP Status return Code?

    503



What would this touch() function do?

update updated_at to current timestamp



ORM (Object Relational Mapper) and Active Record implementation called?

 Eloquent



Laravel uses ___________ to connect to an existing session and general-purpose cache

 Redis



How many types of Middleware in Laravel?

 2    Global Middleware and Route Middleware.



________________ can be defined as a class of elements in which each element has a unique name to that associated class.

C. Namespaces



Which keyword allows the developers to shorten the namespace?

B. use



The cookie can be attached to the response using the ?

B. withCookie() method



By default, all cookies generated by Laravel are encrypted and signed so that they can not be modified or read by the client.

A. TRUE



Laravel uses the Blade @extends directive for defining the child elements

A. TRUE



 What is View?

=> In MVC framework, the letter “V” stands for Views. It separates the application logic and the presentation logic. Views are stored in resources/views directory. Generally, the view contains the HTML which will be served by the application.

Example

Observe the following example to understand more about Views −

Step 1 − Copy the following code and save it at resources/views/test.php

<html>

   <body>

      <h1>Hello, World</h1>

   </body>

</html>


Step 2 − Add the following line in Routes/web.php file to set the route for the above view.


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

   return view('test');

});


Step 3 − Visit the following URL to see the output of the view.

    http://localhost:8000/test


Step 4 − The output will appear as shown in the following image.

HELLO, WORLD




2. What is Procedure ?

A SQL procedure is a group of SQL statements and logic, compiled and stored together to perform a specific task. 

A stored procedure in Structured Query Language is a group of logical statements stored in the database for performing a particular task. It is a subprogram consisting of a name, a list of parameters, and Transact-SQL statements.



3. What is Trigger?

Triggers is a database object similar to a stored procedure that is executed automatically when an event occurs in a database.

A trigger is a piece of code executed automatically in response to a specific event occurred on a table in the database. A trigger is always associated with a particular table. If the table is deleted, all the associated triggers are also deleted automatically.



4. What is Void(0) ?

 It means “no type”, “no value” or “no parameters”, depending on the context. We use it to indicate that.

The javascript:void(0) can be used when we don't want to refresh or load a new page in the browser on clicking a hyperlink

<a href = "javascript:void(0);"> 



5. What is Encapsulation ?

Encapsulation can be used if the properties of the object are private and updating them through public methods.

Encapsulation in PHP can be achieved using the implementation of access specifiers.

Encapsulation is used to hide internal views from the client.

 Object-oriented programming in PHP is achieved by using the concept of Encapsulation which is used for information hiding. It reduces the easy-accessibility of attributes of the present class. Getter and Setter methods are used for avoiding external unwanted access. It also helps in validating new values assigned to the properties.

In short, Encapsulation in PHP is the process of hiding all the secret details of an object that actually do not contribute much to the crucial characteristics of the Class.




7. What is Web page and Website ?

=> 

Web Page:

A webpage has a unique URL address to access that particular page. 

A webpage is a single page of a website. 

Web page can be a video related, image related or document type page. 

A webpage may contains all of the above and also links to other web pages. 

A webpage can be build using different programming languages like PHP, Python etc.  

A web page can be divided into two types, i.e. 'static webpage', 'dynamic webpage'. 

Webpage is relatively easy to develop.


Website: 

Website makes with several webpages linked through hyperlinks. 

The cool thing is, every webpage inside a website are connected/linked using same domain name, so that, we can remember it easily.

The hole website and internal web pages are also build using same programming language.

A website can contain comment box, chatbox, article posting etc. 

Website can be of many types like, affiliate websites, E-commerce websites, dating websites and etc.

A Website is a 'Single-page Website' when it has only one web page and contains every related things in it.




8. What is Lazy Loading and Eager Loading ?

=> 

Lazy Loading: Also called deferred loading. 

To improve performance and overall speed only the needed contents are loaded and when requirement comes necessary page assets are loaded as a lazy loading. 

for example: 

If you’re an instagram user, you’ve probably seen this feature several times before. Next time you use Instagram, visit a popular page and notice that photos do not load until a user scrolls down to where those photos are. 

Web pages are able to load quicker with just the immediately-needed images. 


Eager Loading:

Eager loading is the action of force-loading all the assets on a page at once. It loads related entities, even if the visitor never scrolls down to it. 

You may have seen eager loading in action before as well. If you have ever visited a page with a lot of photos or videos that displayed a loading screen, that’s eager loading. 

Eager loading allows you to load all of your resources at once, but it can lead to much slower speeds and increased bandwidth and resource usage. 


https://advancedwebtuts.com/video-tutorial/what-is-difference-between-laravel-eager-vs-lazy-loading-use-of-with-method



9. What is Carousel ?

Website carousels, also known as carousel sliders, refer to a slideshow of photo or video content on a website. Dynamic carousels display various content of the same type or topic at a certain motion, speed, and time while static carousels are navigated manually with side buttons or arrows.




10. Dependency Injection  ?

Dependency Injection  is the ability of an object to supply dependencies of another object.

Dependency in programming is an approach where a class uses specific functionalities of another class

The process of creating an object for some other class and let the class directly using the dependency is called Dependency Injection. 

Dependency Injection is the process of injecting class dependencies into a class through a constructor or setter method. 

It mainly has three classes involved:

Client Class: This is the dependent class and is dependent on the Service class.

Service Class: This class provides a service to the client class.

Injector Class: This class is responsible for injecting the service class object into the client class


https://appdividend.com/2022/01/23/laravel-dependency-injection/



11. Service provider ?

Service providers are the central place of all Laravel application bootstrapping.

Your own application, as well as all of Laravel's core services, are bootstrapped via service providers.

In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.

The service providers listed in Config/app.php providers array will be automatically loaded on the request to your application. We can add  our own services to this array to add more functionality to your application.

For example:

AuthServiceProvider,

BusServiceProvider,

MailServiceProvider, etc.

code: php artisan make:provider CategoryServiceProvider


https://www.codemag.com/Article/2212041/Dependency-Injection-and-Service-Container-in-Laravel



PHP:

PHP is a server-side scripting language.

PHP used for web development.



Laravel:

Laravel is free ,Open source PHP web framework.

Laravel is MVC(model-view-controller) architectural pattern.

 


Object Oriented Programming:

Advance features and major concept was introduced from version PHP5

Reduce complex risk in web application.



PHP | OOP - Classes and Objects

Classes and objects are core of OOP.

PHP itself is OOP.

In Laravel, almost everything works on classes and objects


OOP: OOP is used to write programs in an organized way, and to organize programs using OOP we group all of the functions and variables according to the particular topics.


There are some concept of OOP's

Class:

1. Class is a set of object which shares common characteristics/ behavior and common properties/ attributes.
2. Class is not a real world entity. It is just a template or blueprint or prototype from which objects are created.
3. Class does not occupy memory.
4. Class is a group of variables of different data types and group of methods.

Object: 

It represents real life entities. An object consists of : 
1. State: It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with other objects.


Polymorphism : 

Polymorphism is the concept with the help of which single action in different ways can be performed. It is derived from two Greek words: poly and morphs. “poly” means many, and “morphs” means forms. Henceforth, polymorphism implies many forms.

Polymorphism = poly(many)+ morphism(shape)

The two types of polymorphism are compile-time polymorphism and run time polymorphism. Compile-time polymorphism is performed by method overloading and runtime polymorphism by method overriding. Runtime polymorphism, also called Dynamic Method Dispatch, is a process wherein a call to an overridden method is resolved at runtime despite compile-time. Herein, the overridden method is called through a reference variable of a parent class. Also, Runtime polymorphism cannot be achieved by data members.

Polymorphism in OOP is of two types

  1. Run time polymorphism (overriding)
  2. Compile time polymorphism (overloading)


Abstraction :

Abstraction is the concept of object-oriented programming that “shows” only essential attributes and “hides” unnecessary information. 

Encapsulation :

  • Encapsulation suggests that one class must not have access to another class’s (private) data. Increase code reusability: Think of various objects of a single class. To declare hundreds of objects, we had to define the class only once with the help of encapsulation.

Constructor : 

Constructors are the member functions of the class whose job is to initialize the object. Following are certain characteristics of constructors: Their name is same as that of the class whose member they are. They do not have any return type, not even void. They can be explicitly defined by the programmer.

Destructor :

Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed.

Inheritance :

The capability of a class to derive properties and characteristics from another class is called Inheritance.




ARRAY FUNCTIONS IN PHP:

array() - creates an array

ex: 

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

there are three types of arrays:

  • Indexed arrays - Arrays with numeric index
  • array(value1, value2, value3, etc.)

  • Associative arrays - Arrays with named keys
  • <?php
    $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
    echo "Peter is " . $age['Peter'] . " years old.";
    ?>

  • Multidimensional arrays - Arrays containing one or more arrays
  • $cars=array
      (
      array("Volvo",100,96),
      array("BMW",60,59),
      array("Toyota",110,100)
      );


array_change_key_case()

Change all keys in an array to uppercase:

<?php

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

print_r(array_change_key_case($age,CASE_UPPER));

?>

O/p: Array ( [PETER] => 35 [BEN] => 37 [JOE] => 43 )



Array_chunk() Function  :

Splits an array into chunks of arrays
<?php
$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
print_r(array_chunk($cars,2));
?>


array_column()

Returns the values from a single column in the input array

<?php
// An array that represents a possible record set returned from a database
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Peter',
    'last_name' => 'Griffin',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Ben',
    'last_name' => 'Smith',
  ),
  array(
    'id' => 3809,
    'first_name' => 'Joe',
    'last_name' => 'Doe',
  )
);

$last_names = array_column($a, 'last_name');
print_r($last_names);


array_combine()

Create an array by using the elements from one "keys" array and one "values" array:
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");

$c=array_combine($fname,$age);
print_r($c);
?>

array_count_values()

Counts all the values of an array

<?php

$a=array("A","Cat","Dog","A","Dog");

print_r(array_count_values($a));

?>

O/p: Array ( [A] => 2 [Cat] => 1 [Dog] => 2 )


array_diff()

Compare the values of two arrays, and return the differences:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_diff($a1,$a2);
print_r($result);
?>


array_diff_assoc() Function

Compare the keys and values of two arrays, and return the differences
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"red","b"=>"green","c"=>"blue");

$result=array_diff_assoc($a1,$a2);
print_r($result);
?>
o/p: Array ( [d] => yellow )    


array_diff_key() Function

<?php

$a1=array("a"=>"red","b"=>"green","c"=>"blue");

$a2=array("a"=>"red","c"=>"blue","d"=>"pink");

$result=array_diff_key($a1,$a2);

print_r($result);

?>

O/p: Array ( [b] => green )



array_fill() Function

The array_fill() function fills an array with values.
<?php
$a1=array_fill(3,4,"blue");
//array_fill(index, number, value)
print_r($a1);
?>

o/p: Array ( [3] => bluex [4] => bluex [5] => bluex [6] => bluex )

Array ( [0] => red )    




array_fill_keys() Function

Fill an array with values, specifying keys:
<?php
$keys=array("a","b","c","d");
$a1=array_fill_keys($keys,"blue");
print_r($a1);
?>
o/p: Array ( [a] => blue [b] => blue [c] => blue [d] => blue )



array_filter() Function

Filter the values of an array using a callback function:

<?php
function test_odd($var)
  {
  return($var & 1);
  }

$a1=array(1,3,2,3,4);
print_r(array_filter($a1,"test_odd"));
?>
o/p: Array ( [0] => 1 [1] => 3 [3] => 3 )


array_flip() Function

Flip all keys with their associated values in an array:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
?>
o/p: Array ( [red] => a [green] => b [blue] => c [yellow] => d )




array_intersect() Function

Compare the values of two arrays, and return the matches:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_intersect($a1,$a2);
print_r($result);
?>
o/p: Array ( [a] => red [b] => green [c] => blue )


array_intersect_assoc()Compare arrays and returns the matches (compare keys and values)
array_intersect_key()Compare arrays, and returns the matches (compare keys only)
array_key_exists()Checks if the specified key exists in the array
array_keys()Returns all the keys of an array


array_map() Function

The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.
<?php
function myfunction($num)
{
  return($num*$num);
}

$a=array(1,2,3,4,5);
print_r(array_map("myfunction",$a));
?>
o/p: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )





array_merge() Function

Merge two arrays into one array:
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
o/p: Array ( [0] => red [1] => green [2] => blue [3] => yellow )



array_merge_recursive() Function

<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge_recursive($a1,$a2));
?>
o/p: Array ( [a] => red [b] => Array ( [0] => green [1] => yellow ) [c] => blue)

The array_merge_recursive() function merges one or more arrays into one array.

The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.



array_multisort() Function

Return a sorted array in ascending order:
<?php
$a=array("Dog","Cat","Horse","Bear","Zebra");
array_multisort($a);
print_r($a);
?>

o/p: Array ( [0] => Bear [1] => Cat [2] => Dog [3] => Horse [4] => Zebra )



array_pad() Function

Return 5 elements and insert a value of "blue" to the new elements in the array

<?php

$a=array("red","green");

print_r(array_pad($a,5,"blue"));

?>

o/p: Array ( [0] => red [1] => green [2] => blue [3] => blue [4] => blue )


array_pop()Deletes the last element of an array
array_product()Calculates the product of the values in an array
array_push()Inserts one or more elements to the end of an array
array_rand()Returns one or more random keys from an array
array_reduce()Returns an array as a string, using a user-defined function
array_replace()Replaces the values of the first array with the values from following arrays


array_replace_recursive() Function

Replace the values of the first array with the values from the second array recursively:

<?php

$a1=array("a"=>array("red"),"b"=>array("green","blue"),);

$a2=array("a"=>array("yellow"),"b"=>array("black"));

print_r(array_replace_recursive($a1,$a2));

?>

o/p: Array ( [a] => Array ( [0] => yellow ) [b] => Array ( [0] => black [1] => blue ) )


https://www.w3schools.com/php/php_ref_array.asp




-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


Short One statement answers:



Object:
i. A real life entity is an object, like person, place or thing. 

Array: 
i. An array is a collection of similar data elements stored at contiguous memory location. An array is a special variable, which can hold more than one value at a time.

Class: 
i. Class are a blueprint or a set of instructions to build a specific type of object and like pre-defined class we can create own.


Why we use class?
i. Classes help you take all the properties and behaviors of an object in your program, and combine them into a single template.
ii. To build user-defined data types.


Why we use objects?
i. It is related to high programming language, Using objects codes are easier to read, write and maintain. 


Why do we need programming language?
i. Programming languages use classes and functions that control commands. It directs a computer to complete these commands over and over again., so people do not have to do the task repeatedly.


Why are interpreters needed?
i. For executing directly. Interpreter is a program for executing programming language input without generating machine language. Display error one by one bcz at a time reads Single statement. Directly generate machine code.


Why I could not write the code directly, if I know the instruction set of the underlying processor?
i. Yes, You can!


Why are compilers needed?
i. For translate and to create an executable program. Compiler is primarily used for programs that translate source code from a HLL to a LLL to create an executable program. Intermediate object code will be generated.


Why we use OOP?
i. OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function. 
ii. OOP language allows to break the program into the bit-sized problems that can be solved easily (one object at a time). The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost
iii. OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.”~ Alan Kay [Inventer]




Abstraction

Encapsulation:

Inheritance:

Polymorphism:




------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------



Interview QUS :

1. Programming language VS Language ?

=>

hint: Decision making language.

Language has no desicion making capability.


2. Why HTML does not a Programming Language?

=>

hint:


3. CSS?

=>

hint: Interactive Website


4. JS?

=>

hint: Client-side programming Language.


5. JQuery?

=>

hint: JS library.

Front end framework


6. Data Vs Information?

=> Data is a collection of numbers, alphabets and special symbols. Ex: akhilesh

Information is a collection of data.


 



hint: Data is a specific fact which can be store.

Raw data is unprocessed computer data. This information may be stored in a file, or may just be a collection of numbers and characters stored on somewhere in the computer's hard disk. For example, information entered into a database is often called raw data. The data can either be entered by a user or generated by the computer itself. Because it has not been processed by the computer in any way, it is considered to be "raw data." To continue the culinary analogy, data that has been processed by the computer is sometimes referred to as "cooked data."


Data is a collection of facts, while information puts those facts into context. While data is raw and unorganized, information is organized. Data points are individual and sometimes unrelated. Information maps out that data to provide a big-picture view of how it all fits together.



Meta Data -> Data within a Data.


Database -> A database is information that is set up for easy access, management and updating. Computer databases typically store aggregations of data records or files that contain information, such as sales transactions, customer data, financials and product informatio



5. Update VS Upgrade

=> Update is for an application or software


Upgrade => The entire system of mobile or computer changed is the upgrade.




----------------- 6/4/22-----------------


&nbsp;

Full form: No/non breaking space, It create a single space.


Pre tag

Full form: Pre formated document.


HREF :

Full form: Hypertext References.


*********************************************

gopalpram@gmail.com

Mail format:

Subj: Assignment Date

Name: SK 

Time: 9:00 - 12:00


Q>

A>


Files are attached, please check once.


-------------------- 8 Apr 2022 --------------------


1. Open tag : There are no any backslash operator. ex: <html>, <head>

2. close tag: There are one backslash operator. ex: </html>, </head>

3. empty tag: In this tag Open Tag and  close tag are in a single tag it means there is no different open tag and close tag. Ex: <br>, </br>,<hr> , <img>

4. non-empty tag: There are separate open tag and close tag. Ex: <p> ..</p> ,



Element:

If you write a statement into a particular tag which can change the format of this statement those tags are called element.

In element there is no need to close tag.

Ex: <b> tag changes the statement.



Attribute:

If you pass some parameters to an element which can change the  structure of the statement those parameters are called attribute.

Ex: <font size, color>



Tag:

Everything write within an HTML file is a tag.

An HTML tag is a piece of markup language used to indicate the beginning and end of an HTML element in an HTML document. As part of an HTML element, HTML tags help web browsers convert HTML documents into web pages

Ex: <br>, <table>



List: List is a specific structure. In html we have 3 types of list.


1. Unordered list: there is no any sequence of ordered value

Ex: <ul></ul>


2. ordered list: There are a sequence of values.

ex: <ol></ol>


3. defination list: In this list the element represent in a dictionary format.

ex"

<dl>

<dt></dt> -- title of defination

<dd></dd> -- data of defination

</dl>



HTML is a tag based language.

H>W>

* Folder:

    1. image

            A. Family image

            B. Friend image

            C. Tour image

    2. Video:

            A. Family video

            B. Friend video

            C. Tour video


    3. Music

            i. Rabindra Sangeet

            ii. Pop/Dj

            iii. Adhunik


Table is a structure where rows and columns are there.


H>W> 2>

tBL2.HTML

3X3 A-i



cellpadding: This attribute create the space between table data with outer cell border


cellspacing: This attribute create the space between cells



---------------*11Apr 22-------------------*


Spanning: Colspan = Merging 2 columns

Rowspan = Merging 2 rows.



Rules

1. Draw the table in your copy

2. Draw the dotted line to complete the table

3. Find the no of rows and columns

4. Write the code


  __________________

 | A   | B  |  C   |

 __________________

 |     .      .       |

 __________________


Task 1:


  __________________

 | A   | B  |  C   |

 __________________

 |     .  D    .       |

 __________________

 | E   | F  |  G   |

 __________________



RowSPAN:


  __________

 |    | B  |

      ______

 | A  | C  |

       ______

 |    | D  |

 ___________


.


 



Form Form is a structure where we can input fields.

An HTML form is a section of a document which contains controls such as text fields, password fields, checkboxes, radio buttons, submit button, menus etc


inside the form:

1. input type: text, dob, data, password, number, file

2. button: radio, submit, reset

3. boxes: select box, check box,



VALIDATION

Enter the value into predefined format.

1. Basic validation:

Email, Required

2. Data format Validation: JS

proper email id validation, password validation,

phone no validation



CSS

CAseCading Style Sheet. It is a designed language

CSS is the language we use to style an HTML document.

CSS describes how HTML elements should be displayed.



WHY CSS IS CALLED CASECADING?

the css can create multiple properties or we can apply multiple property in a single element by using CSS.


So, It is called CASECADING.


When one or more styles are applied to the same element. CSS performs a set of rules called cascading which evaluates the strength of Specificity of the two applied styles and determines the winner i.e the style rule which has more weight wins. if the two rules have same weight then the rule applied last wins.


Types of CSS:

It has 3 types,

1. Inline CSS: In this Css we can apply same style into each and every lines of the element.


Inline CSS contains the CSS property in the body section attached with element is known as inline CSS. This kind of style is specified within an HTML tag using the style attribute.


EACH & EVERY LINE

Ex:

<p style="color:red;...">Para</p>

here,

style tag => Attribute

Color => Property

Red => value

color: red; => declaration



2. Internal CSS: In this CSS Same style or differnet styles apply the elements using only one declaration.


This can be used when a single HTML document must be styled uniquely. The CSS rule set should be within the HTML file in the head section i.e the CSS is embedded within the HTML file.


Without Repeating Same Style can be applied properties inside style tag.


Ex: <style>

  p{ color: aqua;   }

</style>


here,

  p => element / selector

  color =>property

  red => value

  color: red; => declaration

 






3. External CSS:

In this CSS, the CSS file will call outside of the main page.



External CSS contains separate CSS file which contains only style property with the help of tag attributes (For example class, id, heading, … etc). CSS property written in a separate file with .css extension and should be linked to the HTML document using link tag. This means that for each element, style can be set only once and that will be applied across web pages.





SELECTOR:

It has 4 types of selector in Internal CSS.

1. Element Selector:

In this selector, Element can use for calling the CSS.


2.  ID selector:

Different Ids can use inside the elemets and access by # operator.


3.    Class selector:

Different Classes can use inside the elements and access by . operator.


4.      Multiple Selector:

We can apply multiple element, id, & class selector as a Multiple selector.




We can divide CSS selectors into five categories:


    Simple selectors (select elements based on name, id, class)

    Combinator selectors (select elements based on a specific relationship between them)

    Pseudo-class selectors (select elements based on a certain state)

    Pseudo-elements selectors (select and style a part of an element)

    Attribute selectors (select elements based on an attribute or attribute value)


This page will explain the most basic CSS selectors.


Universal Selector


The universal selector (*) selects all HTML elements on the page.



**********************18-4-22----------



href= hypertext references


1> Which Css executes first, give it proper example?

=> An external stylesheet contains CSS in a separate file with a .css extension. This is the most common and useful method of bringing CSS to a document.


And This is the first loaded Css applied on HTML tags or classes or ids.


After that, An internal stylesheet resides within an HTML document.

And It is the second loaded Css applied on HTML tags or classes or ids.


Atlast, Inline Css comes and it is executed and over-writing all Css applied earlier.





JAVASCRIPT 

It is a client side programming language.


JavaScript, often abbreviated JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. Over 97% of websites use JavaScript on the client side for web page behavior, often incorporating third-party libraries


Why JS is called Prog lang?

It can take decision.


3> History of JS?

Brendan Eich

Netscape navigator

James gosling => Java founder

jame gosling Market popularity takes then livescript rename as

Mocha => Livescript => Javascript


In javascript is there any lang as Java?

=>no

Java is only used in business purpose in JAVASCRIPT.


Why JS is called Scripting language?

=> It is because  jS code is only execute into the script tag, so it is called Scriting language.


Why JS is called untyped prog lang?

=>because We do not declare any datatype for declaring a variable. so it is untyped.


Why JS is called loosely typed prog lan?

=> Every Untyped prog lan is called loosely typed prog lang. IN JS it is also a untyped prog lan, so it is also loosely tyoed prog lang.



Advantage of JS, Characteristic of JS, Usage of JS

=>

1. Add functionality

2. validate form

3. Client to server communucation

4. Updation





----------------20-4-22----------------


Javascript Display Function

1. document.write

2. alert

3. confirm

4. prompt

5. console.log



Syntax of  JavaScript

<body>

<script>

</script>

</body>




TASK:

1>Find the forward series and also find the sum of all values of the series.

2> Take 3 variable Find Biggest to smallest

3> Take 2 value find the swapping the value.]

4> Take a number find the factor of a given no



Operator is a specific symbol that occurs between operand.

1. Arithmetic op

2. Relational op

3. Logical op



H.W>

TAKE A NUMBER  CHECK THE NO IS.

TAKE A NUMBER  CHECK THE NO IS armstrong OR NOT.



parseInt = This function can convert string type to Int type.



Camel case notation:

If any alphabet is capital within a given word this notation is called CAMEL CASE notation.



TASK> TAKE A NUM FIND THE FACTORIAL OF A GIVEN NO USING PROMPT

  4! = 24



::selection{

  background-color: #dddd2a;

  color:white;

}


-----------------------22-4-22---------


We have two selector for taking values from a form 1. name 2. id


Rules of Name selector in JS:

a. Take name attribute into the from tag.

b. Take the name attributes into the input types.

c. Use a JS event which call a return a function

d. Create the same function name into the script tag for taking values from your form.



JAVASCRIPT EVENT:

It is an attribute which perform a specific task

In JS event, Every event start with ON  keyword, and call or return a function.


RULES OF ID SELECTOR:

a. Use if attribute into the inputs

b. Use a JS event which call a return a function

c. Create the same function name into the script tag for taking values from your form.

d.


---------------------------25-4-22----------


VALIDATION

Email VALIDATION:


gopal ->


saif@gmail.com

saif.123@gmail.com

saif@ejob.com

saif@ejob123.com

saif@ejob.co.in

saif name

@ after name of gmail

. after domain of gmail

ejob.co   domain of gmail

{2,3}$   2,3 no of letter

[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$



Display Tag in JS:

a. <p> tag

b. <span> tag

c. <div> tag



MOBILE VALIDATION:

a. Non Empty

b. Not < 10

c. Not > 10

d. Not use alphabet/sp. char

e. start with 9,8,7,6


OnCLICK VS ONSubmit


Onclick We can use onClick more than 1 time into a form.

OnSubmit We use only 1 time in the form.


PASSWORD VALIDATION:

1. not empty

2. <8 digits

3. min one numeric value

4. min one upper case

5. min one lower case

6. min one special char



----------27-4-22--------


JAVASCRIPT EVENT:

It is an attribute which perform a specific task

In JS event, Every event start with ON  keyword, and call or return a function.


Javascript event:

Onclick: This event will work when the user click into the input field.

OnDBLclick: when the user double click on the input field.

Onblur: When the user leave the input field.

Onchange: When the user change the input field.

OnFocus: When the user come back/focus into the input field.

onkeyup: When the user's  keyboard key up after pressing.

onkeydown:This event will work When the user's  keyboard next key down while pressing.

onload:

onmouseoverout:



FRAMEWORK: FRAME WORK:

Maintaining a structure doing a work is called Framework.

1. FrontEnd Framework: ReactJS, Angular,

2. Backend Framework: Codeignitor, Laravel, CakePHP.


MVC architecture.

JQUERY: IT is a library of JAVASCRIPT

IT IS ALSO CALLED A FRONTEND FRAMEWORK.



Why do we learn JQUERY?

The purpose of jQuery is to make it much easier to use JavaScript on your website.

Reduce the complexity.

Fast execution.

More secure.



How to write jquery?

Download the library of Jquery.

Use CDN.


CDN: Content Delivery Network

if the user do not download the jquery manually, they can access the library online with internet connection. This network is called CDN.



extension: .js

Company: Google, Microsoft CDN companies.


$(this) : In jquery, $(this) keyword indicates the last selector of your code.



What are the Selector in Jquery.

=> If id and class are not work then use NameSelector.



JQUERY EVENT:


-------------------------------------2-5-22


== is used for comparison between two variables irrespective of the datatype of variable. === is used for comparision between two variables but this will check strict type, which means it will check datatype and compare two values.



PHP: Personal Homepage,

=> PHP:Hypertext PreProcessor

It is a server side programming language.



why php is hypertext preprocessor

=> It is because data can pass to the server side and processing into the server then it will print the output in the client side. so before print it will process into the server that is why it is called hypertext preprocessor.


php is called hypertext preprocessor because php libraries are already compiled and processed. when any person request any php page in browser address bar that request first go to server for example Apache is running on that server. then server interpret php files and return back response in form of HTML



How to run PHP?

=> we need a server for run php script. and The server is present in the cross platform.


cross platform - It can run in any OS.

ex: xampp, wamp


X: cross platfrom

A: Apache = Local server

M: Mariadb/Mysql = Database name

P: PHP = Programming language

P: Perl =Programming language



Why php is called untyped programming language?

=>

It is because we do not declare any datatype for a variable.


Why it is also called loosly typed prog lang?

=> it is because no datatype required for a variable. and it is a untyped lang that's why.



Syntax:

<?php


?>


Localhost:

It is a default server. It is called default because one default IP(127.0.0.1) is present in any cross platform.



-------------------------4-5-22-------


1. Take 2 variables swap btn 2 varibles usnig 3 vari

2. Prime or not

3. factor of a no also, sum of factors

4. armstrong no


-----------+6-5-22+--------------


In php we have two methods use in form tag,

a. GET - (Default) - data show in the url.

b. POST - data cannot show in the url.


In php we have four methods,

a. GET

b. POST

c. PUT

d. DELETE


Super global variable - It is a variable which can store or access the value from your interface.

The syntax of the super global variable is $_ALinCAP['input__NAME']


If you use GET method then we can use, $_GET[] or $_REQUEST[] super global variable.


If you use POST method then we can use, $_POST[] or $_REQUEST[] super global variable.




QUERY STRING:


query string is a technique where we can pass the information one page to another page.


The syntax of the query string is


?id=value


The syntax of multiple querystring is


?id1=val1&id2=val2...

where id represnt the input name of your form and value represent the inputed value



ISSET() -

Thsi function check your value will present or not.


\



TASKS

1. take a num from user find the factorial of a given no,.

2. take 3 inputs find the biggest and smallest no



  ::: ARRAY :::


Array is a variable, which can store the similar types of data,


a[5]

a is the name of the array,

containing 5 elements,


| 4 | 1 | 7 | 8 | 9 |

  0   1   2   3   4

0 index

4 value

cell/pocket



Array in PHP"


It is a variable which can store different types of datatype.


Types of arary in PHP:

a. Index array/ Numerical array

= it is an array where we can store the data and access the data by using the index number.



b. Associative array

= In this array,we can store the data or access the data by using KEY. There is no required of any index no for factching the data.

There is key-value pairs.



c. Multi-dimentional array

= Array within an array is called multi-dimensional array.




Display function of array:

a. print_r()

b. var_dump()

echo implode(" ",$a);



TASK:

Take an Index array print the array using echo, where user can insert or delete the element but echo can not be changed.



TASK:

TAke an associative arrays, print the keys and values separatedly?


-------------------------


Array Function


1. Array function is a function which can take the array and manipulate the array.


Sort arranging in asc order.



Array functions:

array_pop : This array remove the last element out of the array

array_push: this function insert the elements into an existing array at the end.

array_reverse: This function reverse the array out of the array.

The array_reverse() function returns an array in the reverse order.

Array_shift : this function remove the first element of the array.

array_sum : this fun addition the numerical value into the aray.

array_combine: This function combine the same no of elements array between two arrays where one array element represent the key and another one is value.



Count: Returns the no of elements.



array_marge :

this fun merging the aray one after another.



Implode : This function convert array into string.



explode : thsi fun covert string into array.



sizeof : how many pockets are in the array.



count : how many elements in the array.



HW>

TAKE 4 index array, merging the array using array_combine function.


------------------


a> Take a sentence, find the first and last word from this given sentence.



is_array() : this function will check provided variable is array or not.


TASK: array(1,2,3,4,-1,0,-2,0,0,7)



String function: String function is a function where we can take the string or manipulate the string.



md5(): The full form of md5 is Message Diagest algorithm 5

It is an encryption algorithm, which can convert your data into 128bit hash value or 32bit encrypted value.



H>W>

Take 2 index array, first merge this array then convert into a string. Reverse of the given string and find the first alphabet of the given string.


H>w> Take a word "Apple is" Find how many vowels and consonent are present.



-------- ------




------- -------



-----------------16-5-22-----


A Session is a super global varaible that can pass information from one page to multiple page.

We use another super global variable for declaring another session variable as

$_SESSION['session_name'] = value;



session_start() function: This function is used at the begining of session variable declaration, It can help to store the value in the session variable and also print the value into different pages for the variable.


used for Initialize the session.


#CookieFILES

------------------18-5-22-------

MODULE 3


Data is a specific fact which can be stored.


Database : It is an memeory where we can store the data.


DBMS: (DATABASE MANAGEMENT SYSTEM)

It is a system where we can store the data, manipulate the data or access the data in an organized way.


TYPES:  1. Files based

Data stored into file format.


        2. RDBMS

Relational database management system, Data stored into table format.


SQL = Structured query language

It is a database language which is used to comminucate to our database.



Query =

If you ask to some question to database and database will return the ans this will called query.



DATABASE : mwf9-12

T.N. - student



HTTPS: HTTP SECURE SOCKET LAYER



----------------- 20-5-22 -----


Task1=>

Take a sentence from user print the first alphabet of each word.




task 2=>

Take a Sentence "Apple is a fruit." Output will print "elppA is a tiurf".

jader hoye geche etta koro

Take a Sentence "Apple is a fruit." Output will print "elppA is a tiurf".

only first and last word will reverse



SELECT * => Select * statement return all the tuple with attribute in your virtual desktop.




SELECT => select statement return the specific tuples.



WHERE CLAUSE =>

the where clause return the attribute tuples with specific requirement.  



ORDER BY STATEMENT =>

Orderby statement return the tuples value in ascending order.



GROUP BY => this statement group rows that have the same value into summary based.


The groupby statement is offen used with aggregate function (COUNT, SUM, MAX, MIN, AVG) to group the result set by one or more colums.




------ 23-5-22 -----------


HAVING CLAUSE: the where keyword couldnot be used with aggregate function.



JOINING:

There are 4 types of join

1. Inner join:

=>

Return records that have matching value in each table.



2. Left outer join:

=>

Return all records from the left table and the matched record from right table.

those which are not matched print null.



3. Right outer join:

=>

Return all records from the right table and the matched record from left table.

those which are not matched print null.



4. Full join:

=>

Return all records when there is a match either right or left table.




SQL OPERATOR

1. between ... AND


The between operator select value within a given range.


2. LIKE


The like operator is used in a where clause to search for a specified pattern in a where clause.


% all

_ only one



IN operator:

In operator allows you to specify multiple value in a where clause.



SUB QUERY:

=>

Query with in a query is called SUBQUERY. It is also called Nested query.


select name, roll

from std

where roll in (select roll from stu2 where roll > 2 )


--------------------------------

Q> 13-4-22  form1.html

! How to implement language[] in js , jq.



************* 27-5-22 ******


Alter table statement is used to modify an existing table.



Unique key: Is a set of one or more fields / columns, of a table that uniquely identify the database table.

Unique key can hold null value.


alter table tn

add column cn dt UNIQUE



Primary key: It is also a unique key but it do not store null value;

UNIQUE + NOT NULL


null value store hba na bola existing table a column add kra jai na ;



create table parent (roll int(200), name varchar(200), address varchar(200), PRIMARY KEY(roll));


Foreign key: Foreign key is a key used to like 2 tables together.


A foreign key is a field in one table that refers to the primary key in another table, where primary key is set this table is called Parent table, where foreign key is set to child table.


------------- 30-5-22---

Trigger is a set of SQL statement that reside in system memory with unique names.


Trigger is a statement that is executed automatically by system as a side effect of a modification to the database.


We have 2 types of trigger,

before trigger and after trigger.


Syntax:

create trigger [TriggerNAME]

[before/after]

{Insert/Update/Delete} on [tableNAME]

{for each table(row/col)}

set

[trigger body]



* before/after - time of the trigger.

* insert/update/delete - event of the trigger.




STORED PROCEDURE:

Store Procedure - A procedure (often called a store procedure) is a sub routine like a

sub program in a regular computing language,stored in database.



database >  Add routine > routine name > type : procedure >

defination: select * from emp


is deterministic: check

NO SQL


CREATE PROCEDURE `abcd`() NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER select * FROM emp


Execute |> run...




NORMALIZATION:

It means Dividation.

Anomaly reduction.


Normalization is the process to eliminate data redundancy and enhance data integrity in the table.


name | dname | did | hod no | hod name | floor

raja | it | 101 | 123 | abc | 3

manish | cse | 102 | 234 | mno | 2

rajib | ee | 107 | 456 | bcc | 5

rajesh  | it  | 101 | 123 | abc | 3


insert / delete /  update anomaly..


name | dname

raja | it

manish | cse

rajib | EE

rajesh | it



dname | did | hod no | hod name | floor

it | 101 | 123 | abc | 3

cse | 102 | 234 | mno | 2

ee | 107 | 456 | bcc | 5



TYPES OF NORMALIZATION:

1. 1NF: 1st Normal form.

in this normal form, there is no any use of duplicate or multiple values into a single tuple.



Name | Course | Address

Rahul | C | howrah

Raja | C++, JAVA | kolkata


Name | Course | Address

Rahul | C  | howrah

Raja | C++ | kolkata

Raja | JAVA | kolkata



R:(A->B)

R:(AB->C)




2. 2NF :

It must satisfy the 1NF.

There is no partially dependency occur in 2NF.

        

        __|

       |  \/

R:(A   B   C   D)

   |   |       /\

    -----------|


R:(AB -> D)

R:(B  -> C)




3. 3NF:

It must satisfy the 2nf form.

There is no transitive dependency occur.


 If A->B and B->C are two FDs then A->C is called transitive dependency.



A relation is in BCNF, if and only if, every determinant is a Form (BCNF) candidate key.



MODULE 4:


www.facebook.com >

enter email:

enter password:

login >>



The MySQLi Extension (MySQL Improved) is a relational database driver used in the PHP scripting language to provide an interface with MySQL databases.

 


mysqli_connect()

it is a driver function which connects to the database.


The connect() / mysqli_connect() function opens a new connection to the MySQL server.


24---


mysqli_fetch_assoc() =

This driver function reduce the database tuples into a associative array where the array key represent the attribute name and the value represent the tuple value from this given attribute.


Assoc- associative array.



----3-6-22


Student registration -

student name roll address parent_name percentage gender file

$_FILES[]


multipart/form-data =

it is an attribute which is used for sending the files from client side to server side.

This attribute can encrypt your files into multiple paths where we access the data to sending into the form to the server.


mysqli_num_rows()=

This function return the tuples number from your giver array.



6-6-22--------


in_array() =

It can check the element is present into the array or not.


AJAX = ajax create connection between server and client site via internet.


AJAX - Asynchronous Javascript and xml. =

It is not a programming language, It is a technique where it can communicate client side to server side and server side to client side.

but bring the result into client side.


Types of AJAX =

i) Jquery ajax

ii) Javascript ajax


Asynchronous = data reload automatically.

XML = Extensible markup language.

XmlHttpRequest - class


Topology no 200 is OK

Topology no 404 is Error


---- 15-6----


Multi image import =





-------------------gaps


mysqli - The full form of mysqli is (MySQL Improved). It is a database driver.


mysqli_connect - It is driver function which connects your database.


select addr, dept_no

from emp

where dept_no IN

(Select dept_no from dept)


----- 1-6-22-----


DIE - It is inbuild function in PHP. the DIE function print the message and exists the current php script.


mysqli_connect_error - This driver function can returns the errors.


CRUD operation - create, retrive, update, delete


include() - The impact the code into another file.


Trigger task:

Suppose you have 25000 in your bank account, you send 5000 in your friend's account. find your account and friends account. After transaction my account and friends account both updated.


mysqli_query() - This driver function execute your query into your database. It has two  parameters. First parameter is connection parameter and second parameter is sql parameter. which can start query.





-------------22-6


OOPs: Object oriented programming and systems


Software approache:

1. Procedure: C

2. oops approache: C++, JAVA, PYTHON, PHP

3. MVC approach (Model view controller):


Complexity:

1. Time complexity

2. Space Complexity



For debugging time complexity Procedure language switches to OOP.


Reduce debuggingtime provide by OOPS.

Provide security



OOPS:

1. OBJECT: It is a real world entity.


2. CLASS: Blue print of the Object.


3. MEMBER FUNCTION: Member functions are those functions which is present into the class and perform different performance.


4. MEMBER VARIABLE: Member variables are those variables which are present into one class and help to perform different performance into the different member function.


5. ACCESS SPECIFIER: How to access Member function and member variables into one class to another.

  i) public: In this access specifier member variable and member function access inside the class and outside of the class.


  ii) private: Member variable and member functions can access only inside the class.


  iii) protected: Member variable and member functions can access inside the class and immidiate child class



RULES:

  1. Class name and file name must be equal.


  2. The first alphabet of the class name always be CAPITAL.


Syntax:

<?php


class ClassName{

  member variables + member functions;

}


create object for class;


access member variables/ member functions by object.


?>


Filename: ClassName.php


/////

TASK:


Name:

Email: validation

Password: 10dig, special char

Image:


Submit:


Echo print in action page.

//////


----------------- 24-6-22-----


3 Major principles of Object Oriented Programming:

1. Encapsulation: Rapping up a data and method in a single unit is called a encapsulation.


2. Inheritance: In this principle data and method of a parent class can access by the child class.


3. Polymorphism: You can take more than one form or having a single form with manyu different implementation ways.


 The word “poly” means many and “morphs” means forms, So it means many forms.



  INHERITANCE:


[A] <= [B]

SINGLE LEVEL


[A] <= [B] <= [C]

MULTI LEVEL


[A] [B] <= [C]

MULTIPLE

NOT EXECUTABLE

  1. INTERFACE

  2. TRAIT

[A] <= [B] [C] [D]

HIERARCHICAL






Interface are similar to abstract classes. The difference between interfaces and abstract classes are:


Interfaces cannot have properties, while abstract classes can

    

All interface methods must be public, while abstract class methods is public or protected

    

All methods in an interface are abstract, so they cannot be implemented in code and the abstract keyword is not necessary


Classes can implement an interface while inheriting from another class at the same time



Interface:

An interface is just like a normal class with replace of class keyword into interface.


the interface contains no data variables, and function must be terminated which can be implemented into child class.


A class that implements an interface must implement all of the interface's methods.


TRAITS comes from biology, its meaning the characteristic moves from parent to child.

In php, Trait is just like a normal class used in parent class as a "trait" keyword.

all the functions in traint can access by child class using "use" keyword.




Constructor is a special type of member function in oop.

When object initialize the contructor calls automatically at the beginning, in php we write constructor as a magic function "__construct()".


DESTRUCTOR is a special type of member function in oops. When object become destroy then destructor call automatically at the end.

the syntax of destructor in php is "__destruct()".




Advantages of Encapsulation:


Data Hiding and Abstraction: Unnecessary details, internal representation and implementation are hidden from the end-users for protection of data structure and the Class. Data access is prohibited from members of other classes by creating private methods. It protects the internal state of any object by keeping member variables private and preventing any inconsistent state. It is the enclosing of data and related operations into that object.


    Note: Encapsulation is used to hide internal views from the client.

  Data security: Encapsulation helps in making data very robust and secured, as the data and member functions are wrapped together to form an object. All the tasks are done inside without any external worry and it also makes life very easy.

  Reduces complexity: Encapsulation helps in reducing development complexity of the software by hiding the details of implementation and exposing the methods or operations.

    Reusability: There are instances, you don’t have to re-write same functionality that you inherited from the parent class.


  Reliability: You can make the class read-only or write-only by writing SET or GET methods.

    Easier testing of code: Encapsulated PHP code is easy to test as the functions used for testing child class ensures the testing of parent class functions also.

    Increased


flexibility: Class variables can be accessed by GET or SET methods increasing flexibility. It is easy to maintain as the internal implementation can be changed without changing the code.



TASK HW


You have one parent class and another child class.

It has 2 constructor in parent and child class both with different statements.

You have one object of child class.

print both constructor messages using this object.


1. single level inh

2. One obj of child

3. both class has constructor

4. Extends, Child thn parent.


TYPES OF POLYMORPHISM:

1. Compile time (function overloading)

2. Runtime (function overriding)


Function overloading not done..


Function Overloading: Function overloading contains same function name and that function performs different task according to number of arguments. For example, find the area of certain shapes where radius are given then it should return area of circle if height and width are given then it should give area of rectangle and others. Like other OOP languages function overloading can not be done by native approach. In PHP function overloading is done with the help of magic function __call(). This function takes function name and arguments.



in the interface, the method body is not defined. Only the name and the parameters are being defined.


interface Logger {  

    public  

    function execute();  

}


an abstract class is one being partially implemented by any developer. It might contain at least one abstract method which is basically a method without any written code. It just contains the name and the parameters and has been marked as “abstract”.

 

By definition, an abstract class is simply a function definition whose purpose is to serve the programmer by telling them the method in question must be implemented in a child class.


abstract class AbstractClass {  

    abstract protected  

    function getValue();  

    public  

    function printOut() {  

        print $this - > getValue().  

        "\n";  

    }  

}


$this = Reference of the object.


Interface Class

  |

Abstract Class


Interface class supports multiple inheritance feature

|  

Abstract class does not support multiple inheritances.


This does not contain a data member.

|  

Abstract class does contain a data member.


The interface does not allow containers.

|  

The abstract class supports containers.



An interface class only contains incomplete members which refer to the signature of the member.

 |  

Abstract class contains both incomplete(i.e. abstract) and complete members.


Since everything is assumed to be public, an interface class does not have access modifiers by default.

 |

An abstract class can contain access modifiers within subs, functions, and properties.


Any member of an interface cannot be static.  

|

Only a complete member of the abstract class can be static.




SCALAR TYPE DECLARETION:

Scalar type decl. is sometime call TYPE HINTING.  It basically allows us to specify the datatype of the variable.



GENERATOR FUNCTION:

A generator function just looks like a normal function, except that instead of returning a value a generator yield as many values as needs to. Any function containing yield is called GENERATOR FUNCTION.


TASK: Take a number in static, print the reverse series of the given number and also print the average using generator function.



PDO: the full form of Php data objects.

It is a consistent way to access databases.

It is also called a class which can pass the data in secure to your database.



MVC ARCHITECTURE:

  Model view controller: It is an architecture. Controller represent the request handler, View repesent the user interface, and model represent the business logic.


The architecture of MVC:


user-req>  Controller

  <res- (Request Handler)


  views               Model

  (User interface)[forminsert.hp]          (logic)[oops 1.Insert, 2. Select, 3. Update]


User sends the request to the controller.

Controller check this request logic is present or not in the model, If it is present the value will pass to the model through controller from you and modify to the database. Then the controller sends the response to the user.



CODEIGNITER(MVC) - PHP , Laravel, Cake PHP.


It is a PHP backend framework which support the MVC architecture.


CodeIgniter is a powerful PHP framework.



How to find CI_Controller class?

=>

ci_mwf9-12 -> system -> core -> Controller.php


URL :

localhost/ci_mwf9-12/index.php/Welcome/index


localhost/ci_mwf9-12/

=> base url()


index.php/Welcome/index

=>

base index / controller name / function name



How to find CI_Model class?

=>

system -> core- > model.php


----------8-7-22-------


View to View communication cannot done.


How to find base URL?

-> buildNAME -> application -> config -> config.php


line no 26.


How to import into the Helper?

=>

-> buildname -> application -> config -> autoload.php

92 line


$autoload['helper'] = array();

$autoload['helper'] = array('url');



IMAGE:



DATABASE:


How to configure your database?

=>

Build name -> application -> config -> database.php

76 line


How to connect to your database?

=>

It has 2 ways..

no1. Automatic connection:

  Build name -> application -> config -> autoload.php

  line no 61


$autoload['libraries'] = array();


$autoload['libraries'] = array('database');



no2. Manual connection:

 using Controller manually put..


 function __construct(){

    $this->load->library("database"); // manual connection

  }


-------------------------------11-7-22----


// model loading can done with the help of parent::__construct() otherwise, raise error


model call from constructor

before that call parent constructor.


if controller has ifelse part same thing is present in model. BIdirectional way communication.


stdClass Object  = standard class object


 <td><?php echo $res['name']; ?></td> error  while pass as OBject.

 $res->name show result pass as Object ;


 $res['name'] when using pass as Array;



$query->num_rows()

 get the no of rows in model php


 ------------ 13-6-22 ---------


display


edit


--------- 18-6-22 -----

session


$this->load->library("session");// session_start()


path-> build->library -> session ->session.php


all library names are in lowercase.



------ 22-7-22 ----

Query Builder


  Codeignitor gives you access to a query builder class. This pattern allows information to retrived, inserted and updated in your databases with minimul scripting.



-----24-7


Difference between MariaDB and Mysql

. Mysql is written in C and C++ language.

. It was initially relased on 1995

. The performance of MySQl is not that greate when compared to MariaDB

. It does not provide a replacement for MariaDB

. Data masking is done in MYSQL.

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

Module 1:

1. What is Js?[T]

2. What are the advantages or characteristics of JS? [t]

3. Disadvantage of JS [t]?

4. All validations in javascript and jquery both with form validation.

5. All Jquery events.

6. All javascript events.

7. What is Jquery? What is CDN? Advantage and disadvng of Jquery? [t]

8. Types of Js selecter with example.

9. Types of Css. 


Module 2:

1. Difference between array and array_in php. [t]

2. Types of array in php with example. [t]

3. what is session and cookie with proper example. 

4. what do we use session and cookie in real life. [t]


Module 3:

1. All my notes and assignments perform in previous.


Module 4:

1. Crud operation in query string, session and ajax.

2. what is ajax. [t]

3. Adv of using ajax. Types of ajax. [t]


Module 5:

1. All my notes and assignments perform in previous.

2. [v.imp ** ] Crud operation in PDO.


Module 6:

1. Codeignitor: 

a. Notes send in previous in CIG.

b. Diff bet Library and helper.

c. Holder structure in codeIgnitor.

d. Crud operation in Query Sting, query builder and session.

e. What is routing and application of the routing.


Module 7:

1. What is WebService?

2. What is Postman?

3. Application of WebService?

4. Picture in my document

5. Advantage of Json.


Module 8:

1. What is Api?

2. Which Api do you use in your project.

3. What is CMS? 


Module 9:

1. Why do we use Wordpress?

2. What is plugin?

3. Advantage of using plugin?

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

QuestionsQuestion Type
From opps everything,constructor,destructor, types of inheritance in details syntax , types of polymorphism syntax, abstract class syntaxTheory
why method overloading is not work in php in place of that what we used ?Theory
why multiple inheritance not work?Theory
IN My sql
• Second hight salary
• Third highest salary
• Avg sal
• Found student count from each department if we have 3 different department
Practical
In php what is super global variable? what is Query string?Theory
what is code ignitor ?what architecture follows ,in details discussed controller, view , model, what is brain of mvc architecture ?Theory
what is session, cookie with examples?Practical
Difference between post and get?Theory
How many type of array?Theory
Difference between session and cookie AND real life example session and cookie;Theory
Find tha maximum salary and minimum salary in sqlPractical
How many member in 101,102,103,104 department no?Practical
What is OOPS AND MVC?Theory
What is polymorphism and inheritance and encapsulation?Theory
Type of inheritance ?Theory
What is interface AND trait AND abstra class?Theory
How to work MVC ?Theory
What does PEAR stands for?Theory
Explain the difference between dollar message and $$message.Theory
What is the difference between “echo” and “print” in PHP?Theory
How to perform server side validation in php.
Show by a Html form.
Practical
What is the meaning of "enctype= multipart/form-data" in PHP?Theory
What is the difference between require() and require_once()?Theory
What is the difference between implode() and explode() in php?Theory
What is the difference between == and === in PHP?Theory
Create a view Form and take email id and send a test mail to the id using Codeigniter.Practical
What is ternary operatorTheory
What is split() functionTheory
What is abstraction ? Give a real life example ( doing codes)Theory+Practical
What is the difference between oop and sop(structured oriented programming)Practical
state your project work ( how far you can explain) starting from A - Z everything without seeing anything ( means codes of project work)Practical
Is it possible to switch between country to States to districts to city and then insert these in the database tables (According to your chosen option first country then states and district after that) ?Practical
Give a real life example application of AJAX with codes.Theory+practical
What is default constructor?Theory
What is class constructor?Theory
Difference between cookies and session?Theory
What is Hooks , Helper in Codeigniter explain the code and usageTheorey
What is Cross Site Scripting and Cross site Resource Forgery , how can we prevent the same in CodeIgniter ?Theory+practical
What is JSON ? json_encode() ? json_decode() ? explainTheory+practical
Multiple File Upload , File Upload Preview ?Theory+practical
jQUERY PreventDefault() exampleTheory+practical

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


 ------------------------------------

Mail 

https://www.youtube.com/watch?v=XCQHqoV-tnc

------------------------------------


composer create-project laravel/laravel nameLAProj


enter to folder and run >> 


php artisan serve


https://devdocs.io/laravel~8-guides-the-basics/


make controller: 

php artisan make:controller UserController


@if($names=='Saif')

<h2>hello, {{ $names }} </h2>

@elseif($names=='sam')

<h2>hello, {{ $names }} </h2>

@else

<h1>Unknown</h1>

@endif


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

    <h4>{{$i}}</h4>

@endfor


$data=["saif",'akash','babu','rajkumar','tonny'];

        return view('users',["users"=>$data]);


Route::get("users",[UsersController::class,'loadView']);



@include('inner')


@foreach($users as $user)

<h2>{{$user}}</h2>

@endforeach


<script>

    var data = @json($users);

    console.warn(data)

    console.warn(data[0])

</script>


<x-header componentName="Users" />


Route::post("users",[UsersController::class,'getData']);

Route::view("login",'users');


 $req->validate([

            'username'=>'required',

            'password'=>'required'

        ]);


@if($errors->any())

    @foreach($errors->all() as $err)

        <li>{{$err}}</li>

    @endforeach

@endif


 <span style="color:orange;">@error('username'){{$message}}@enderror</span>


 $req->validate([

            'username'=>'required | max:10',

            'password'=>'required | min:5'

        ]);


middleware: 

Global MiddleWare

Grouped 

Routed


users form

<h1>User Login</h1>


<form action="users" method="POST">

    @csrf

    <input type="text" name='username' placeholder='Enter User Id'>

    <span style="color:orange;">@error('username'){{$message}}@enderror</span>

    <br>

    <br>

    <input type="password" name='password' placeholder='Enter Password'>

    <span style="color:orange;">@error('password'){{$message}}@enderror</span>

    <br>

    <br>

    <button type='submit'>Login</button>

</form>


php artisan make:middleware checkAge


global middleware:

 public function handle(Request $request, Closure $next)

    {

        echo "Global Message for All Page from Middlewre";

        if($request->age && $request->age <18){

            return redirect('noaccess');

        }

        return $next($request);

    }


Route::view("noaccess","noaccess");

noaccess.blade.php >>

<h2>You cannot access our website</h2>

kernal.php >> 

 protected $middleware = [

        // \App\Http\Middleware\TrustHosts::class,

        \App\Http\Middleware\checkAge::class,


kernal ->

 protected $middlewareGroups = [ ...

'protectPage' => [

            \App\Http\Middleware\checkAge::class,

        ]

]


middleware/ checkAge.php

 public function handle(Request $request, Closure $next)

    {

        echo "Group Message for All Page from Middlewre";

        if($request->age && $request->age <18){

            return redirect('noaccess');

        }

        return $next($request);

    }



Route > web.php =>


Route::group(['middleware'=>['protectPage']], function (){

    Route::view("users",'users');

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

        return view('welcome');

    });

});



php artisan make:middleware ageCheck


ageCheck middleware fun

  public function handle(Request $request, Closure $next)

    {

        if($request->age && $request->age <18 )

        {

            return redirect('noaccess');

        }

        return $next($request);

    }


define in kernal.php 

  protected $routeMiddleware = [

        'protectedPage' => \App\Http\Middleware\ageCheck::class,


call from web.php from route


Route::view('home','home')->middleware('protectedPage');

Route::view("users",'users')->middleware('protectedPage');




Database Configuration: >> .env file

DB_DATABASE=blog

DB_USERNAME=root

DB_PASSWORD=


config -> database.php -> env folder configuration access


use App\Http\Controllers\UserController17;

Route::get("users",[UserController17::class,'index']);


use Illuminate\Support\Facades\DB;


class UserController17 extends Controller

{

    function index(){

        return DB::select('select * from users');

        // echo "DB conncection will be here";

    }

}


Modal :

 Map database table with class name 

Define database structure

 Write Business logic



Create:

 php artisan make:model User

 php artisan make:controller UserController18


For model create controller.


Route::get("users18",[UserController18::class,'getData']);



use App\Models\User;


class UserController18 extends Controller

{

    //

    function getData(){

        return User::all();

    }

}


class User extends Model

{

    use HasFactory;

    public $table='employee';

}



API 

reqres.in/api/users?page=1



Http Client >>


use Illuminate\Support\Facades\Http;


class UserController19 extends Controller

{    

    function index(){

        // echo "API call will be here ";

        $data=Http::get("https://reqres.in/api/users?page=1");

        return view('user19',['collection'=>$data['data']]);

    }


<h1>User19list</h1>

<table border='1'>

    <tr>

        <td>Id</td>

        <td>Name</td>

        <td>Email</td>

        <td>Profile Pic</td>

    </tr>

    @foreach($collection as $user)

        <tr>

            <td>{{$user['id']}}</td>

            <td>{{$user['first_name']}}</td>

            <td>{{$user['email']}}</td>

            <td> <img src="{{$user['avatar']}}" alt="">  </td>

        </tr>

        

    @endforeach

</table>



use App\Http\Controllers\UserController19;

Route::get("users19",[UserController19::class,'index']);



Http Request >>

get / post / put / delete / head / patch / options


php artisan make:controller UserController20


Route::put("users20",[UserController20::class,'testRequest']);

// Route::delete("users20",[UserController20::class,'testRequest']);



<form action="users20" method="POST">

    @csrf

   {{ @method_field('PUT')}}

    <input type="text" name='username' 




SESSION>>>

UserAuth

login.blade.php

web.php [update]

profile.blade.php



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

       if(session()->has('user')){

              session()->pull('user',null);

       }

       return redirect('login');


});


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

       if(session()->has('user')){

              return redirect('profile');

       }

       return view('login');


});


 function userLogin(Request $req){

        $data = $req->input('username');

        $req->session()->put('user',$data);

        // echo session('user');

        return redirect('profile');

    }



<h2>Hello, {{ session('user') }}</h2>

<a href="/logout">Log Out</a>


<!DOCTYPE html><html lang="en"><head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

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

    <title>Document</title>

</head><body>


    <h1>User Login</h1>

    <form action="/user" method="POST">

        @csrf

        <input type="text" name='username' placeholder='Enter User name'> 

        <!-- <span style="color:orange;">@error('username'){{$message}}@enderror</span> -->

        <br>        <br>

        <input type="password" name='password' placeholder='Enter Password'>

        <!-- <span style="color:orange;">@error('password'){{$message}}@enderror</span> -->

        <br>        <br>

        <button type='submit'>Login</button>

    </form>    

</body></html>


Flash session: 22

   function storeM(Request $req){

        $data= $req->input('username');

        $req->session()->flash('user',$data);

        return redirect('store');


@if(session('user'))

<h3>Data saved for {{session('user')}}</h3>

@endif



Route::view('store','storeuser');

Route::post('storecontroller',[StoreController::class,'storeM']);



Upload File in Laravel:>?>>


Route::view('upload','upload');

Route::post('upload',[UploadController::class,'index']);



<form action="upload" method="POST" enctype="multipart/form-data">

    @csrf

    <input type="file" name="file"><br><br>

    <button type="submit">Upload File</button>

</form> 


 function index(Request $req){

        return $req->file('file')->store('img');

    }




<<<< Localization >>>


Route::view('profile','profile24');


Route::get('/profile/{lang}', function($lang) {

       App::setlocale($lang);

       return view('profile24');

});



<h1>{{__('profile.welcome')}}</h1>

<br>

<a href="">{{__('profile.list')}}</a><br>

<a href="">{{__('profile.about')}}</a><br>

<a href="">{{__('profile.contact')}}</a>


D:\SAIF\LARAVEL\BLOG\LANG

en

     auth.php

     pagination.php

     passwords.php

     profile.php

     validation.php

hi

   profile.php

ko

   profile.php



<?php 

return [

    "welcome"=>"Welcome To Profile",

    'about'=>'about',

    'list'=>'list',

    'contact'=>'contact'

];

?>


app > config >> app.php

line no 85


'locale' => 'ko',

//default language



 $data =  Member::paginate(5);



<div>

    {{$members->links()}}

</div>

<style>

    .w-5{

        display: none;

    }


  function addData(Request $req){

        $member = new Member;

        $member->name = $req->name;

        $member->email = $req->email;

        $member->address = $req->address;

        $member->save();

        return redirect('add');

 public $timestamps = false;



<<<  DELETE >>>

 function list( ){

        $data=Member::all();

        return view('list28',['members'=>$data]);

    }


    function delete($id){

        $data = Member::find($id);

        $data->delete();

        return redirect('list');

    }



  <td><a href={{"delete/".$item['id']}}>Delete</a></td>


Route::get('list',[MemberController28::class,'list']);

Route::get('delete/{id}',[MemberController28::class,'delete']);




<<< EDIT >>>

<form action="/edit" method="post"> @csrf

    <input type="hidden" name='id' value={{$data['id']}}>

    <input type="text" name='name' value="{{$data['name']}}"> <br><br>

    <input type="text" name='address' value="{{$data['address']}}"> <br><br>

    <input type="text" name='email' value="{{$data['email']}}"> 



class Member extends Model

{

    use HasFactory;

    public $timestamps = false;

}


Route::get('edit/{id}',[MemberController28::class,'showData']);

Route::post('edit',[MemberController28::class,'update']);


function showData($id){

        $data = Member::find($id);

        return view('edit',['data'=>$data]);

    }


    function update(Request $req){

        $data=Member::find($req->id);

        $data->name = $req->name;

        $data->address = $req->address;

        $data->email = $req->email;

        $data->save();

        return redirect('list');

    }


use Illuminate\Support\Facades\DB;



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

        return view('list30',['data'=>$data]);

        

        return DB::table('members')

        ->where('address','Kolkata')

        ->get();

        

        return (array) DB::table('members')->find(4);

        

        return (array) DB::table('members')->count();

        

        return DB::table('members')

        ->insert(["name"=>"Sakhtiman",

            "address"=>"Kolkata", 

            "email"=>"Sakhtiman@saif.com"]);


        return DB::table('members')

            ->where('id',15)

            ->update(["name"=>"Sakhtiman",

                    "address"=>"Delhi", 

                    "email"=>"Sakhtiman@saif.com"]);


        return DB::table('members')

            ->where('id',12)->delete();


  <td>{{$item->id}}</td>

        <td>{{$item->name}}</td>

        <td>{{$item->email}}</td>

        <td>{{$item->address




<<< AGGREGATE FUN >>>

use Illuminate\Support\Facades\DB;

class UserController31 extends Controller

{

    //

    function operations(){

        // return DB::table('members')->sum('id');

        // return DB::table('members')->max('id');



<<< JOIN >>>

use Illuminate\Support\Facades\DB;


 return DB::table('employee')

        ->join('company','employee.id','=','company.employee_id')

        ->select('*')

        ->where('employee.id',2)        

        ->get();

    




<< MIGRATION >>


php artisan make:migration create_test_table

blog>database> 2022_08_18_073024_create_test_table

public function up()

    {

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

            $table->id();

            $table->string('name');

            $table->string('email');

            $table->timestamps();

        });

    }

php artisan migrate




php artisan make:migration create_test5_table

php artisan migrate

php artisan migrate:reset

php artisan migrate:rollback --step 3

php artisan migrate --path=/database/migrations/2020_09_21_141958_create_test5_table.php

php artisan migrate:refresh

 php artisan make:migration create_test25_table

 php artisan migrate

 php artisan migrate:rollback --step 2

 php artisan migrate:refresh

 php artisan migrate:reset

 php artisan migrate --path=/database/migrations/2022_08_18_075449_create_test25_table.php



<<< SEEDING >>>


php artisan make:seeder MembersSeeder


database > seeders > MembersSeeder


use Illuminate\Support\Facades\DB;

use Illuminate\Support\Str;


 public function run()

    {

        //

        DB::table('members')->insert([

            'name'=>Str::random(10),

            'email'=>Str::random(10).'@gmail.com',

            'address'=>Str::random(10)

        ]);

    }


save data into database code:

php artisan db:seed --class=MembersSeeder


no of times it execute create dynamic entries



<<< STUB >>>

 php artisan make:controller UserController36


function index(Request $req){

        return "Some code";

    }

}


stubs > controller.plain.stub > 

  function index(Request $req){

        return "Some code";

    }

 php artisan stub:publish


php artisan make:controller UserController36_2

php artisan make:controller UserController36_3


function comes automatically.


IN MODEL "


 public $timestamps = false;


add it inside stubs > model.stub file.

 php artisan stub:publish


 php artisan make:model MemberModel36


statement comes automatically.



LARAVEL 8 updates

jetstram

model factory class

migration squashing

job batching

improved rate limiting

improved maintenance mode

closure dispatch/ chain

dynamic blade components

tailwind pagination views

time testing helpers

improvements to artisan serve

event listener improvements

bug fixes



<<< Maintenance Mode >>> 38

php artisan down


php artisan up


php artisan down --secret="xyz123abc"


php artisan up



<<< MIGRATION >>>

php artisan migrate


php artisan migrate:reset


php artisan make:migration create_test_table


php artisan migrate


php artisan migrate:rollback


php artisan migrate --path=/database/migrations/2022_08_19_055614_create_test5_table.php



<<< UPDATE >>

php -v


For new pRoject:

laravel new blog


composer.json update  file>>

php, guzzle

framework, collision, ignition.


run

composer update



<< JETSTREAM >>

laravel -v

composer global remove laravel/installer

composer global require laravel/installer


laravel new jetBlog --jet


npm install && npm run dev


41....



<<< ACCESSOR >>>

php artisan make:controller MemberController42

use App\Models\Member;


  function index(Request $req){

        return Member::all();

    }


Route::get('member',[MemberController42::class,'index']);



Member

class Member extends Model

{

    use HasFactory;

    public $timestamps = false;

    function getNameAttribute($value){

        return ucFirst($value);

    }

    function getAddressAttribute($value){

        return ($value. ", India");

    }

}



<< MUTATOR >>


 public function setNameAttribute($value){

        return $this->attributes['name']='Mr. '.$value;

    }


    public function setAddressAttribute($value){

        return $this->attributes['address']=$value.', India';

    }


 function index(Request $req){

        // return Member::all();

        $member = new Member;

        $member->name='light';

        $member->email='lightman@saif.com';

        $member->address='hydrabad';

        $member->save();

    }




<<< ONE to ONE RELATION >>>


php artisan make:controller MemberController44


use App\Models\Member;

class MemberController44 extends Controller

{

    //

     function index(Request $req){

        return Member::find(8)->companyData;

    }

}


class Company extends Model{}


class Member extends Model{

function companyData(){

        return $this->hasOne('App\Models\Company');

        //  return $this->hasMany('App\Models\Company');

    }

 php artisan make:model Company


Route::get('data',[MemberController44::class,'index']);




<< ONE 2 MANY >>

   function index(Request $req){

        return Member::find(2)->getDevice;

    }


class Device extends Model{}


function getDevice(){

        return $this->hasMany('App\Models\Device');

    }


Route::get('data',[MemberController45::class,'index']);




<<< FLUENT STRING >>>

use Illuminate\Support\Str;



$info ="hi, let's learn laravel";

// $info=Str::ucfirst($info);

// $info=Str::replaceFirst("Hi","Hello",$info);

// $info=Str::camel($info);

$info= Str::of($info)

       ->ucfirst($info)

       ->replaceFirst("Hi","Hello",$info)

       ->camel($info);

echo $info;



<<< ROUTE MODEL BINDING >>>

Route::get('device/{key}',[DeviceController::class,'index']);

// Route::get('device/{key:name}',[DeviceController::class,'index']);



  function index(Device $key){

        return $key;

        // return $key->all();

    }



<< MARKDOWN MAIL TEMPLATE >>

php artisan make:mail SampleMail --markdown=emai

ls.SampleMail


views > email> samplemail.blade.php


@component('mail::message')

# Introduction


The body of your message.


@component('mail::button', ['url' => ''])

Button Text

@endcomponent

<br>

<h1>Hello, Saif!. Comes in to LARAVEL.</h1>


@component('mail::table')

| Laravel | Table | Example |

| ------- | ----- | ------- |

| Col 2 i | Cente |  $10    |

| Col 3 i | Cente |  $10    |

@endcomponent

Thanks,<br>

{{ config('app.name') }}

@endcomponent




web.php

use App\mail\SampleMail;


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

       // return view('welcome');

       return new SampleMail();

});


App\mail > SampleMail.php


<<API>>

php artisan make:controller dummyAPI

 function getData(){

        return ["name"=>"saif", "email"=>"saif@saif.com", "address"=>"Burdwan"];

    }

}



route>api.php

use App\Http\Controllers\dummyAPI;

Route::get("data",[dummyAPI::class,'getData']);



WITH DB CONNECTION GET API>>


use App\Models\Device;

class DeviceController51 extends Controller

{

    //

     function list(){

        return Device::all();

    }



class Device extends Model


Route::get("list",[DeviceController51::class,'list']);


use App\Http\Controllers\DeviceController51;

Api.php



Route::get("list/{id?}",[DeviceController51::class,'list']);



 function list($id=null){

        return $id?Device::find($id):Device::all();

    }




<<< POST DATA >>>

POST .. RAW .. JSON..


 function add(Request $req){

        $device = new Device;

        $device->name=$req->name;

        $device->member_id=$req->member_id;

        $result=$device->save();

        if($result){

            return ["result"=>"Data has been saved"];

        }else{

            return ["result"=>"Operation Failed"];

        }

    }


use App\Http\Controllers\DeviceController53;

Route::post("add",[DeviceController53::class,"add"]);


public $timestamps = false;




 function update(Request $req){

        $device = Device::find($req->id);

        $device->name=$req->name;

        $device->member_id=$req->member_id;

        $result=$device->save();

        if($result){

            return ["result"=>"Data has been updated"];

        }else{

            return ["result"=>"Operation Failed"];

        }

    }



Route::put("update",[DeviceController53::class,"update"]);


DELETE >>

Route::delete("delete/{id}",[DeviceController53::class,"delete"]);


 function delete($id){

        $device = Device::find($id);

        $result= $device->delete();

        if($result){

            return ["result"=>"Data has been deleted"];

        }else{

            return ["result"=>"Operation Failed"];

        }

    }



SEARCH >>>

Route::get("search/{name}",[DeviceController53::class,"search"]);


 function search($name){

        return Device::where("name","like","%".$name."%")->get();

    }



VALIDATE >>


Route::post("validate",[DeviceController53::class,"testData"]);


function testData(Request $req){

        $rules =array(

            "member_id"=>"required |max:4",

            "name"=>"required"

        );

        $validator = Validator::make($req->all(),$rules);

        if($validator->fails()){

            return response()->json($validator->errors(),401);

        }else{            

            $device = new Device;

            $device->name= $req->name;

            $device->member_id = $req->member_id;

            $result = $device->save();

            if($result){

                return ["result"=>"Data has been Saved"];

            }else{

                return ["result"=>"Operation Failed"];

            }

        }

    }



RESOURCE >>

php artisan make:controller MemberConmtroller58 ---resource

public function index()

    {

        return Member::all();

        //

    }


No need to call function, 


Route::apiResource("member",MemberConmtroller58::class);



Sanctum >>

composer require laravel/sanctum


php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"


php artisan migrate


use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;


To use tokens for users ?>>

use Laravel\sanctum\HasApiTokens;


class user extends Authenticatable{

use HasApiTokens, Notifiable;


>> 

php artisan make:seeder usersTableSeeder


>>

use Illuminate\Support\Facades\DB;

use Illuminate\Support\Facades\Hash;


DB::table('users')->insert([

            'name'=>'John Doe',

            'email'=>'johndoe@saif.com',

            'password'=>Hash::make('12345')

        ]);


php artisan db:seed --class=UsersTableSeeder


 php artisan make:controller UserController59


use App\Models\User;

use Illumiate\Support\Facades\Hash;


function index(Request $req){

        $user = User::where('email',$request->email)->first();

        if(!$user || !Hash::check($request->password, $user->password)){

            return response([

                'message'=>['These credentials do not match our records']

            ],404);


        }

        $token = $user->createToken('my-app-token')->plainTextToken;


        $response = [

            'user'=>$user,

            'token'=>$token

        ];


        return response($response,201);



Route::group(['middleware'=>'auth:sanctum'],function(){

// 

});



Route::group(['middleware'=>'auth:sanctum'],function(){


    Route::apiResource("member",MemberConmtroller58::class);

 });


Route::post("login",[UserController59::class,'index']);


https://github.com/anil-sidhu/laravel-sanctum


postman > get > ../api/user > headers > 

key: Authorization Value: Bearer +..token > post




make command >>>

php artisan make:command showDB

app > commands > showDB



 $signature = 'showDB';

 $description = 'Show current Database';

 public function handle()

    {

        $this->info(DB::connection()->getDatabaseName());  


class Kernel extends ConsoleKernel

protected $commands = [

        Commands\showDB::class,

    ];


php artisan showDB



<<  Multiple Database Connection >>


.env


DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=blog

DB_USERNAME=root

DB_PASSWORD=


DB_CONNECTION_SECOND=mysql

DB_HOST_SECOND=127.0.0.1

DB_PORT_SECOND=3306

DB_DATABASE_SECOND=youtube

DB_USERNAME_SECOND=root

DB_PASSWORD_SECOND=


config>database.php



        'mysql2' => [

            'driver' => 'mysql',

            'url' => env('DATABASE_URL'),

            'host' => env('DB_HOST_SECOND', '127.0.0.1'),

            'port' => env('DB_PORT_SECOND', '3306'),

            'database' => env('DB_DATABASE_SECOND', 'forge'),

            'username' => env('DB_USERNAME_SECOND', 'forge'),

            'password' => env('DB_PASSWORD_SECOND', ''),

            'unix_socket' => env('DB_SOCKET', ''),

            'charset' => 'utf8mb4',

            'collation' => 'utf8mb4_unicode_ci',

            'prefix' => '',

            'prefix_indexes' => true,

            'strict' => true,

            'engine' => null,

            'options' => extension_loaded('pdo_mysql') ? array_filter([

                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),

            ]) : [],

        ],




php artisan make:controller ProductController

function list(Request $req){

        // return DB::table('devices')->get();

        // return DB::connection('mysql2')->table('products')->get();

        


using MODEL >>

php artisan make:model Product

php artisan make:model Device


 return Device::all();


class Product extends Model

{

    use HasFactory;

    public $timestamps = false;

    public $connection = 'mysql2';


class ProductController extends Controller

{

    function list(Request $req){

 return Product::all();



<<< UPLOAD FILE USING API >>>


php artisan make:controller FileController



 function upload(Request $req){

        $result=$req->file('file')->store('apiDocs');

        return ['Result'=>$result];


Api.php >>

use App\Http\Controllers\FileController;

Route::post("upload",[FileController::class,'upload']);




<<< IMPORTANT INTERVIEW QUS >>

1. Name aggregate methods of query builder

max min sum avg count


2. What is a Controller?

A controller is the "C" in the "MVC" architecture

Central Unit in MVC

Connect model and View

Router Calls Controller Directly


3. Latest Version and It's Feature

Laravel 9 has a minimum requirement of PHP 8.0

New Design for routes

Anonymous Stub Migrations are kept as default

Laravel 9 has improved themes on an exceptional page

Laravel 9 provides New Query Builder Interface

 major improvements

 Symfony 6.0 support

 Flysystem 3.0 

Laravel 9 has provided default timeout in HTTP clients for 30sec. This step will help avoid hangs occurring in the previous version.

Laravel 9 has shifted from SwiftMailer to Symfony Mailer, which provides more consistency to your application


4. What is PHP artisan

Php artisan is the command line interface/tool included with laravel.

It provides a number of helpful commands that can help you while you build your application easily.


5. What is Data migration in Laravel

Migrations are like version control for your database, which allows your team to easily modify and share the application's database schema. 

In laravel db also structured is controlled by laravel.


6. What is Data Migration in Laravel

Migrations are like version control for your database, which allows your team to easily modify and share the application's database schema.

In laravel db also structured is controlled by laravel.


7. What are Laravel Eloquent?

Laravel's Eloquent ORM is simple Active Record implementation for working with your database. 

  Laravel provide many different ways to interact with your database, Eloquent is most notable of them.


8. What is QueryLog?

Provide the SQL query that is applied by laravel function when we want to perform some operations with database.

dd(DB::getQueryLog());


9. Can we turn off CRSF token?

Yes, we can.

app/http/kernal.php

and disable VerifyCsrfToken Middleware


10. Routing method in laravel

Route::get($url, $callback);

Route::post($url, $callback);

Route::put($url, $callback);

Route::patch($url, $callback);

Route::delete($url, $callback);

Route::options($url, $callback);

Route::any($url, $callback);

Route::match($url, $callback);

Route::view($url, $callback);



11. Define Lumen

Lumen is a micro-framework.

It is a smaller, and faster, version of a building Laravel based services, and REST APIs.


12. What is Dump and Die Method

Use for Print the result such as print_r

But this is little bit advance to print_r

dd()


13. What is Laravel API rate limit?

Provide the limit for HTTP request for load controller and secure website


14.What is default session timeout duration?

120 minutes


15. Encryption and Decryption Password

We can do it with hashing class in laravel 

E.g. Hash::make("Password")


16. What is HTTP middleware?

For filter out requested and check the authentication of users such as user is logged in or out. 


17. What are accessor and mutator in laravel?

Mutator allows you to alter data before it's saved to a database.

Accessor allows you to alter data after it's fetched from a database.


18. List types of relationships available in Laravel Eloquent?

one to one,

one to many,

one to Many(inverse),

many to manym,

has many through,

polymorphic relations


<< C_PANEL >>



------------------------------------------------

------------------------------------------------

LARAVEL 9  made by- taylor otwell

------------------------------------------------

------------------------------------------------



What is Laravel?

Php framework

To develop web app and API

MVC Pattern

Easy to use and learn

Most used app framework


What is framework?

A framework in programming is a tool 

that provides ready-made functions, feature

for fast development.


A framework is a platform for developing software application,

Framework is a common structure for develop applications so that developers don't have to do work from scratch.


Every programming language has framework

PHP: Laravel, Codeignitor

Node: Express

JS: Angular

Python: Django 



Features like, 

Routing,

Easy database connection,'

Managed code,

Ready-made function for session,

Helpers for commonly used functions


Why use Laravel

A large community of developers on web

Fast and simple

regular updates

The command line is awesome 


Different in Laravel an (React, Angular etc)

Laravel is a server-side framework,

You can not make a single page app directly

It can connect with DB

Angular etc an not connect with DB

Angular etc need API

Angular etc need a backend framework



MVC is a pattern in software design commonly used to implement user interfaces, data and controlling logic.



COMPOSER

A Dependency Manager for PHP.

Install Packages with Single Command

Can Update version packagem framework etc

Composer can be used with any frameworks

Similar like NPM in node.


NEW PROJECT >

LARAVEL NEW BLOG9


RUN PROJECT >

php artisan serve


---------------------------------

---------------------------------

PROJECT 

---------------------------------


laravel new eComm-en

php artisan serve

php artisan make:migration create_users_table

 php artisan migrate

 php artisan make:seeder UserSeeder

 php artisan db:seed --class UserSeeder

php artisan db:seed --class UserSeeder 

php artisan make:controller UserController

php artisan make:controller ProductController

 php artisan make:middleware UserAuth

php artisan make:migration create_products_table

php artisan migrate

php artisan make:seeder ProductSeeder

 php artisan db:seed --class ProductSeeder

php artisan make:model Product


php artisan make:migration create_cart_table

php artisan migrate


 php artisan make:model Cart

php artisan make:migration create_orders_table

php artisan make:model Order


------------------------------------------------------------------------

------------------------------------------------------------------------

PROJECT - jetstream

------------------------------------------------------------------------

laravel new multiauth


composer require laravel/jetstream


php artisan jetstream:install livewire


npm install 

npm run dev


database>migrations>users_table>afterLine16

laravel>browser


php artisan migrate

user

user@saif.com

saifusered12


admin

admin@saif.com

saifadmin12


App>providers>RouteServiceProvider>line no 20

Route> web.php > after line 28


php artisan make:controller HomeController


---------------------PART 2-----------------------

laravel new l8 --jet

0

yes


npm install && npm run dev


php artisan migrate




------------------------------------------------------------------------

------------------------------------------------------------------------

PROJECT - Hospital Management System

------------------------------------------------------------------------

laravel new Hospital

composer require laravel/jetstream

php artisan jetstream:install livewire

npm install

npm run dev


changes some in User migration table.


php artisan migrate


Add phone and address field in registration >>

app/models/user.php>line no26

database/migrations/users_table>lineno18

resources/views/auth/register.blade.php> lineno20


user

user@saif.com

saif1234


admin

admin@saif.com

saifadmin12


Route>>

app/providers/RouteserviceProvider > line no 20

routes/web.php > lino


php artisan make:controller HomeController


To remove logo and dashboard>

views>navigation-menu.blade.php > lineno6


body color remove>

views> layouts> app.blade.php > line no22


php artisan make:controller AdminController

php artisan make:model Doctor -m


php artisan make:model Appointment -m


php artisan migrate


php artisan notifications:table

php artisan migrate

php artisan make:notification MyFirstNotification



--------------------- ------------ ----------------------

PRACTICE - CRUD 1

--------------------- ------------ ----------------------

1. Create laravel project

=> laravel new curd1


2. Run server

=> php artisan serve


+. Make UserController

=> php artisan make:controller UserController  


3. Create DB, Update .env file, 

=> create crud1 in mysql db


+. Migrate table for user

=> php artisan make:migration create_user_table


4. Make necessary fields

=>

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

 $table->id();            $table->string('name');

 $table->string('email')->unique();

 $table->string('password'); $table->timestamps(); });



5. upload the table in database

=> php artisan migrate


6. Make Seeder for user values

=> php artisan make:seeder UserSeeder


=> php artisan db:seed --class=UserSeeder

use Illuminate\Support\Str;

use Illuminate\Support\Facades\DB;

 DB::table('users')->insert([

            'name'=>'Ironman'.Str::random(2),

            'email'=>'Ironman'.Str::random(2).'@si.com',

            'password'=>'123'

        ]);



+. Make model for users

=> php artisan make:model User 


+. BLADE PAGES 

=> login.blade.php

@extends('master')

@section('content')    

 <div class="container">

    <form action="login" method="post">

        @csrf


=> register.blade.php

@extends('master')

@section('content')    


 <div class="container">

    <form action="register" method="post">

        @csrf


=> details.blade.php

@extends('master')

@section('content')    


<?php $c=1 ?>            

@foreach ($alluser as $item)            

<tr><th scope="row">{{$c++}}</th><td>{{$item->name}}</td>

@endsection



=> header.blade.php

<li class="nav-item"><a class="nav-link" href="login">Login</a></li>



=> master.blade.php

  {{View::make('header')}}

    @yield('content')

use bootstrap geeting started code here



+. Web.php

use App\Http\Controllers\UserController;


//view all user

Route::get('/',[UserController::class,'details']);

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

    return view('login');

});

Route::post('/login',[UserController::class,'login']);

Route::view('/register','register');

Route::post('/register',[UserController::class,'register']);

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

    if(session()->has('user')){

        session()->pull('user',null);

    }

    return redirect('login');

});



 << USER CONTROLLER >>


use App\Models\User; use Session;

use Illuminate\Support\Facades\Hash;


class UserController extends Controller{

    function login(Request $req){

        $user = User::where(['email'=>$req->email])->first();

        if(!$user || !Hash::check($req->password, $user->password)){

            return "User or Password is not matched";

        }else{

            $req->session()->put('user',$user);

            return redirect('/');                    }    }

    function register(Request $req){

        $user = new User;

        $user->name=$req->username;

        $user->email=$req->email;

        $user->password=HASH::make($req->password);

        $user->save();

        return redirect('/login');    }

    function details(){

        $data = User::all();

        return view('details',['alluser'=>$data]);    } }




----------------------------------------------------------------

Practice - CRUD 2

----------------------------------------------------------------


1. make controllers


2. Authentication


3. make migration table


4. blade view pages


5. route 


6. build all funs 


7. Add middleware

php artisan make:middleware UserAuth


app>http>middleware>UserAuth

kernal >

for global ::lineno 56 protected middleware >

'user_auth'=> \App\Http\Middleware\UserAuth::class,


UserAuth.php >>

public fun handle()

echo "This is inside middleware running";

if($req->age && $req->age <18){ return redirect('noaccess'); }

return $next($req);



Route>> web.php >>

Route::view("users",'users')

Route::view("home",'home')

Route::view("noaccess",'noaccess')



--------------------commands and usage--------------


1. php artisan migrate:refresh --seed

2. php artisan migrate:rollback --step=5

3. php artisan migrate:refresh --seed

4. php artisan migrate:refresh

5. php artisan migrate:fresh

6. php artisan migrate:fresh --seed

7. 


$table->id();

$table->year('birth_year');

$table->text('description');

$table->rememberToken();

$table->integer('votes');

$table->increments('id');

$table->float('amount', 8, 2);

$table->double('amount', 8, 2);

$table->decimal('amount', 8, 2);

$table->date('created_at');

$table->char('name', 100);

$table->boolean('confirmed');

$table->binary('data');

$table->bigInteger('votes');

$table->bigIncrements('id');

$table->foreignId('user_id');

$table->unique('email');

$table->primary(['id', 'parent_id']);


Column modifier:

->after('column')

->autoIncrement()

->default($value)

->nullable($value = true)

->unique();


*:::: Modifing Columns::::*

composer require doctrine/dbal

 $table->string('name', 50)->nullable()->change();


*:::: Renaming Columns::::*

composer require doctrine/dbal

  $table->renameColumn('from', 'to');


*:::: Dropping Columns::::*

composer require doctrine/dbal

   $table->dropColumn('votes');

$table->dropColumn(['votes', 'avatar', 'location']);

$table->dropRememberToken();

$table->dropTimestamps();


*:::: Foreign Key Constraints ::::*

    $table->unsignedBigInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');

$table->foreignId('user_id')->constrained('users');




----------------------------------------------------

-------------------GIT NOTES----------------------





************************

echo "# Cardekho" >> README.md

git init

git add README.md

git commit -m "first commit"

git branch -M main

git remote add origin git@github.com:MRSKSAIFUDDIN/Cardekho.git

git push -u origin main


…or push an existing repository from the command line


git remote add origin git@github.com:MRSKSAIFUDDIN/Cardekho.git

git branch -M main

git push -u origin main


ssh: 

git@github.com:MRSKSAIFUDDIN/Cardekho.git


************************


git init


git add .


git commit -m "first commit"


git remote add origin "LINK"


git remote -v


git push -u origin master


git status


git clone --branch <branchname> <remote-repo-url>



The command to delete a local branch in Git is:

git branch -d  local_branch_name



you do NOT want to delete, with the git checkout command:

git checkout branch_name



 for -- delete --force

git branch -D local_branch_name


The command to delete a remote branch is:

git push remote_name -d remote_branch_name


Create new BRANCH:

git branch dev


Select Branch:

git checkout dev


MERGE BRANCH: with anotherBranch

git merge BRANCHNAME


Push into master origin:

git push -u origin master



----- To restore added files to untracked

git restore --staged nameOFfile

 

---- Delete a file 

rm -rf nameOFfile


----- 

copy git log hashcode and run

git reset  d474ef6f26bc0e4d6898c843482cc2b937759595


-----

git stash

git stash pop

git stash clear


-----

git remote add origin https://github.com/MRSKSAIFUDDIN/learnWeb.git


------

git branch kunal

git checkout kunal    


---------------TO RUN PROJECT

1.Run  

git clone --branch BRANCHNAME 'link projer github'


2.Run composer install


3.Run cp .env.example .env or copy .env.example .env


4.Run php artisan key:generate


5.Run php artisan migrate


6.Run php artisan db:seed


7.Run php artisan serve

----------------------------------------------------

-------------------CLASS NOTES----------------------


1. change in existaning table:


php artisan make:migration Extra_Field_in_User_Table --table=users

//upfunction//

 $table->string('address')->nullable();

 $table->integer('phone')->nullable();

 $table->string('profile_image',500)->nullable();


//down function//

$table->dropColumn('address');

$table->dropColumn('phone');

$table->dropColumn('profile_image');


php artisan migrate


//optional if any error

php artisan migrate:rollback


// make model with migration

php artisan make:model UserAddress -m


php artisan make:model Role -m


// make model with migration with controller

php artisan make:model Role -mcr


H

1. table create using migration name as "education 

details". 

year % couse  institute

2022 9 mca    BWU


2. users table add column "role_id" integer field


3. migrating using integer to BIG INT 'bigInteger'

=>

download from this..

composer require doctrine/dbal


php artisan make:migration int_to_bigINT_user_ph --table=users


//up fun

$table->bigInteger('phone')->change();


//down fun

  $table->integer('phone')->change();


4. multiple image add in php



////////////////19-9-22


php artisan make:seeder UserSeeder


run fun code:

 // DB::table('users')->delete();


        DB::table('users')->insert(array(            

            0 =>

            array(

                'id' => 1,

                'name' => 'Admin',

                'email' => 'admin@demo.com',                

                'phone' => '9874627436',

                'password' => '9874627436'

                      ),            

            1 =>

            array(

                'id' => 4,

                'name' => 'Demo',

                'email' => 'restaurant@demo.com',

                'phone' => '9841105534',

                'password' => '9874627436'

            ),

            2 =>

            array(

                'id' => 5,

                'name' => 'Hashtag BBQ',                

                'email' => 'daniel@hashtagbbq.com',

                'phone' => '9841105534',

                'password' => '9874627436'                

            ),

            3 =>

            array(

                'id' => 6,

                'name' => 'Club Central' ,               

                'email' => 'club.central@gmail.com',

                'phone' => '9064247026', 

                'password' => '9874627436'               

            ),

        ));



// UserSeeder file use DB

use DB;


// DatabaseSeeder.php in run fun

$this->call(UserSeeder::class);


php artisan db:seed


// direct migration and seed run

php artisan migrate --seed


//   remove previous data

        DB::table('users')->delete();


// perticular seeding a seeder

php artisan db:seed --class=UserSeeder



HW> 

1. seeder

2. migrate stepwise rollback

3. multiple image


------------------------21/9/22------------------------------

 $user= new User; // create user


        $user->name = 'raja';

        $user->email='raja@g.com';

        $user->password='com';

        $user->phone='2222';


        $user->save(); //data save




use DB;

use App\Models\User;


use Faker\Factory as Faker;


class UserSeeder extends Seeder

{


    public function run()

    {

        // db query

        // DB::table('users')->delete();


        $Faker = Faker::create();

        

        // using  loop

        for($i=0;$i<5;$i++){

        // using model orm

            $user= new User; // create user


            $user->name = $Faker->name;

            $user->email=$Faker->email;

            $user->password=$Faker->password;

            // $user->phone=$Faker->phone;


            $user->save(); //data save

        }

        

    }

}



code to run

php artisan db:seed --class=UserSeeder


UserController.php

use App\Models\User;

use App\Models\User;

class UserController extends Controller

{

    function create(){

        return view('user');

    }

    function user_post(Request $request){

        $user= new User; // create user


        $user->name = $request->name;

        $user->email=$request->email;        

        $user->phone=$request->phone;

        $user->password='sasasasdad';

        $user->save();

        return back();

    }

}


UserModel:

protected $fillable = [

        'name',

        'email',

        'password',

        'phone'

    ];




user.blade.php:

 

<form action="{{ route('user_create'); }}" method="post">

                    @csrf 

                    <div class="mb-3">

                        <label for="" class="form-label">Name</label>

                        <input type="text" class="form-control" name="name" id="" aria-describedby="emailHelp">          

                    </div>

                    <div class="mb-3">

                        <label for="exampleInputEmail1" class="form-label">Email</label>

                        <input type="email" class="form-control"  name="email" id="exampleInputEmail1" aria-describedby="emailHelp">          

                    </div>

                    <div class="mb-3">

                        <label for="" class="form-label">Phone</label>

                        <input type="number" class="form-control"  name="phone" id="" aria-describedby="emailHelp">          

                    </div>        

                    <button type="submit" class="btn btn-primary">Submit</button>

                </form>


WEB.php

use App\Http\Controllers\UserController;


Route::get('/user_create',[UserController::class,'create'])->name('create');


Route::post('/user_post',[UserController::class,'user_post'])->name('user_create');


// route name is: user_create




HW..

1> form submit

2> Diff ORM DB query.




--------------------23sep


Table add in view blade.


fields add in table


make all view page from Controller.


$data['data']=ind::all();

return view('',$data);


$data=ind::all();

$data=ind::get();

return view('',compact(''));


<< from blade view >>

@foreach($data as $val)

{{ $val -> name}}

@endforeach




--- img upload

form enctype='multipart/form-data'


div > label: upload file

<input type='file'  name="profile_pic">



if ($request->hasFile('profile_pic')) {

      $file_type = $request->file('profile_pic')->extension();


      $file_path = $request->file('profile_pic')->storeAs('images/users', time() . '.' . $file_type, 'public');


      $request->file('profile_pic')->move(public_path('images/users'), time() . '.' . $file_type);


  //  } else {

//

  //    $file_path = $request->profile_image_old;


//    }


GO TO PUBLIC FOLDER: 

create folder>> images >> users


make migration-> extrafiled 'profile_pic'


GOTO CONTROLLER:

add profile pic


$info->profile_pic=$file_path;



HW>> 

col-md-6 col-md-6 


 list   edit, delete



CRUD

name, email, phn_no, image


------------------------------


php artisan make:model customer -mcr


--------------------------------26-9-22--


Controller >> function 


 public function updateaction(Request $req){

        $ctmr = customer::find($req->id);

        $ctmr->name = $req->name;

        $ctmr->email = $req->email;

        $ctmr->phone = $req->phone;

        if ($req->hasFile('imgx')) {

            $file_type = $req->file('imgx')->extension();

            $file_path = $req->file('imgx')->storeAs('images/customer', time() . '.' . $file_type, 'public');

            $req->file('imgx')->move(public_path('images/customer'), time() . '.' . $file_type);

            $ctmr->image=$file_path;

        }

       

        $ctmr->save();

        Session::flash('message', "Special Customer added Successfully");

        return redirect('/');

    }


 public function editaction($id){

        $data = customer::find($id);

        return view('customer.editpage',['data'=>$data]);

    }



blade>> file edit line


  <a href="/edit/{{$item->id}}"> EDIT </a>




editpage.blade.php >>




<!doctype html>

<html lang="en">

  <head>    

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Cafe</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>     

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

  </head>

  <body>

    <div class="container">

        <h3>Update Form</h3>

        <form action="/updateaction" method="post" enctype="multipart/form-data">

            @csrf

            <input type="hidden" name="id" class="form-control" value="{{$data->id}}">  

            <div class="mb-3">

              <label class="form-label">Name</label>

              <input type="text" name="name" class="form-control" value="{{$data->name}}">                      

            </div>

            <div class="mb-3">

              <label class="form-label">Email</label>

              <input type="email" name="email" class="form-control" value="{{$data->email}}">                      

            </div>

            <div class="mb-3">

              <label class="form-label">Phone No</label>

              <input type="number" name="phone" class="form-control" value="{{$data->phone}}">                      

            </div>

            <div class="mb-3">

              <label class="form-label">Image</label>

              <input type="file" name="imgx" class="form-control">   

              <img src="../{{$data->image}}" alt="" srcset="" height="100px">                   

            </div>

            <button type="submit" class="btn btn-primary">Update</button>

        </form>

    </div>

    

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

  </body>

</html>




Route>> web.php



Route::get('/edit/{id}',[CustomerController::class,'editaction'])->name('edit');

Route::post('/updateaction',[CustomerController::class,'updateaction'])->name('updateaction');




Update DB query: 

 public function updateaction(Request $req){

      

        if ($req->hasFile('imgx')) {

            $file_type = $req->file('imgx')->extension();

            $file_path = $req->file('imgx')->storeAs('images/customer', time() . '.' . $file_type, 'public');

            $req->file('imgx')->move(public_path('images/customer'), time() . '.' . $file_type);

      

        }else{

            $file_path=$req->old_img;

        }

       

      

      

        $ctmr =  DB::table('customers')

        ->where('id', $req->id)

        ->update([

            'name' => $req->name,

            'email' => $req->email,

            'phone' => $req->phone,

            'image' => $file_path,

        ]);


        Session::flash('message', "Special Customer added Successfully");

        return redirect('/');


    }





------------- storage blog 

https://tudip.com/blog-post/how-to-integrate-amazon-s3-bucket-in-php-laravel/


https://www.itsolutionstuff.com/post/laravel-amazon-s3-file-upload-tutorialexample.html



****--**-*-**-*-**-* VALIDATION 


$validator = $request->validate([ 

            'page_name' => 'required',

            'url' => 'required|unique:cms,url,' . $id,

            'title' => 'required',

            'description' => 'required',

        ]);




H>W> 


1. name, email, phone, address, education select2, qualification, profile_img[single png jpg format]

2. edit, delete : CRUD

3. Validation all..  [ Session variable error checking, JQ validation, LARAVEL validation ]

4. 


next>> login , middleware, 


----------------------------28sep-------

HW>

1. AJAX VALIDATION

2. use TEMPLATE

3. 


----------------------------30sep----------

https://www.mgtechnologies.co.in/product/cooladmin-dashboard-template


header and footer =>common folder


views >> common folder >> 

header.blade.php 

menu.blade.ph


doctype to head close, paste header part


index, @include('common.header')


footer to end, paste in footer part


index, @include('common.footer')


header to end, paste in menu


index, @include('common.menu')



 



1> Jquery in Modal


2> redirect all done, image portion done


3> car dekho redirect all, with common folder using


* add routes DONE


* make one common for Header, menu, and footer DONE


* add admin in car dekho

DONE


* login in bydefault

DONE


* logout

DOEN


* clean dashboard

DONE





** -------------------------------------------------- **

** ~~~~~~~~~~~~~~~~~~~~ 7-10-22 ~~~~~~~~~~~~~~~~~~~~~ **


user register

Password using HASH

use Hash;


Controller Register function"""

$passwd = Hash::make('1234');

echo $passwd;

die;


Login function""" 

Hash::check($request->password, $data->password)


Session

Middleware


// CarController

Contact us : message send using mail


MAILTRAP


laravel .env file 

line no 31


MAIL_MAILER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=465

MAIL_USERNAME=email

MAIL_PASSWORD="password"

MAIL_ENCRYPTION=ssl

MAIL_FROM_ADDRESS=email

MAIL_FROM_NAME="Saif"


https://www.itsolutionstuff.com/post/laravel-9-mail-laravel-9-send-email-tutorialexample.html


----------------------------------------------

--------------10-10-22------------------------ 


middleware >>


H.W. >>

Account page: 

data in from 

name, email, phone, image

update data

change password

https://www.youtube.com/watch?v=kWEvrHVg8kI

https://www.youtube.com/watch?v=XCQHqoV-tnc



-----------------12-10-22-----------------------


Admin banner

: side pages: title and image upload

: home page: title and multiple image


image of pages, action 

active

inactive


mail enquiry: Date filter validation


Mail: Gmail send mailing




----------------------------------------------

*********************************************


php artisan make:middleware DisableBackBtn



In middlware ]] }} 


$response= $next($request);


$response->headers->set('Cache-Control', 'nocache, no-store, max-age=0, must-revalidate');


$response->headers->set('Pragma','no-cache');


$response->headers->set('Expires','Sat, 01 Jan 2000 00:00:00 GMT');


return $response; 


________________________________

In kernal ]] middleware }}


routemiddleware :


'disable_back_btn' =>

\Ill....\Middleware\DisableBackBtn::class,


    name of middlewre define



____________________________________

Route: web.php


Route::group(['middleware'=>'disable_back_btn'],function() {


});






*********************************************

-----------------14-10-22------------------------------


Design all.

--done


Middleware auth


Mail Format change


name change to Banner

--done



-----------------------18/10




config >> app.php


timezone => UTC 

Asia Kolkata apply



in get

paginate(5)


foreach after table after

{{ $data->links() }}



app >> providers >>

use Illuminate\Pagination\Paginator;


boot(){

paginator::useBootstrap();

}


-----------HELPER FUNCTION---

helpers.php under app


In composer.json add after autoload:


"autoload": {

        "psr-4": {

            "App\\": "app/",

            "Database\\Factories\\": "database/factories/",

            "Database\\Seeders\\": "database/seeders/"

        },

        "files": [

            "app/helpers.php"

        ]

    },

line no 23


 "files": [

            "app/helpers.php"

        ]


Autoload helper function..

In terminal, 

composer dump-autoload


call from controller 

test()

or view=>

{{ test() }}


after hosting-----

composer update




HW>>

Seeder = Role 

1> Admin

2> Driver

3> Customer

DONE


user table=>migrate

admin=1

Done


usertype in register

Done


Role = Customer or driver

Dashboard only, 

//partially done , access through url  DONE PROPERLY


Role = Admin 

Show dsbrd , bnn, enqury

//partially done , access through url 



admin => users list 

//role show  joining wise done


role id save in users table

// as array format Done



helper function

Login Helper function 

fetch user data, 

one fun user data via id, data fetch, use in website..

helper function change menu



*-------------------------------*


if(auth()->user()->roles){

foreach(auth()->user()->roles as $role){

if($role->name =='Time Table' ||

$role->name =='Admin' || 

$role->name =='Supervisor') {

return $next($request);

}

}

}



Route::middleware('Driver')->group(function(){

Route::get('as',[c::class,'c']);

});




-----isadmin migration



if(auth()->user()->roles){

foreach(auth()->user()->roles as $role){

if($role->name =='Admin') {

return $next($request);

}

}

return redirect()->route('user.home');

}



--------------AUTH DOWNLOAD AND INSTALLING----


1> composer require laravel/ui

2> php artisan ui bootstrap --auth

3> npm install && npm run dev

4> composer remove laravel/ui



-----------------------20-10

enquiry reply

DONE


user active 

DONE


driver details 

Name Email password

Phone Address 

LicenceNo CarNo 

experience

Salary Active 

image

DONE



car management system 

name

brand

carNo

pickuploc --

droploc --

date --

time --

person 

gear 

year 

kmpl 

features 

image 

status 

book --

-- DONE




customer details



home page 

6cars

see more


car details show on book now.


Related cars

All except show id


Comments

Popular posts from this blog

[[ ROYAL CAR ]] CHANGE PASSWORD - DYNAMIC BANNER - MULTIPLE IMAGE - LOGIN LOGOUT BACK BUTTON MIDDLEWARE STOP - MAIL DIRECTLY WITH FEEDBACK WITH SAVE IN SQL DB - ADMIN REPLY EXISTING MAILS - DYNAMICALLY CSS CHANGE

Sahari

Linux Terminal