0% found this document useful (0 votes)
38 views9 pages

PHP, MySQL, CI, Laravel Guide

Laravel Interview Questions for all levels of Engineers

Uploaded by

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

PHP, MySQL, CI, Laravel Guide

Laravel Interview Questions for all levels of Engineers

Uploaded by

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

--------- PHP ---------

What is Class and What is object - A class is a template for objects, and an object
is an instance of class.

localStorage : The localStorage object stores data with no expiration date. The
data is not deleted when the browser is closed, and are available for future
sessions

Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance

Encapsulation in Java is a mechanism of wrapping the data (variables) and code


acting on the data (methods) together as a single unit

Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object

https://www.upgrad.com/blog/polymorphism-in-php/

Interface : specifying the public methods that a class must implement

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

Rules for PHP variables:


A variable starts with the $ sign, followed by the name of the variable.
A variable name must start with a letter or the underscore character.
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )

CONSTRUCTOR : PHP allows developers to declare constructor methods for classes.


Classes which have a constructor method call this method on each newly-created
object, so it is suitable for any initialization that the object may need before it
is used.

DESTRUCTORS:PHP 5 introduces a destructor concept similar to that of other object-


oriented languages, such as C++. The destructor method will be called as soon as
all references to a particular object are removed or when the object is explicitly
destroyed or in any order in shutdown sequence.

Is multiple inheritance supported in PHP?

function sub(){ } , div();

What is pass by value and pass by reference

function add_some_extra(&$string)
{
$string .= 'and something extra.';
}

$str = 'This is a string, ';


add_some_extra($str);
echo $str;

Function overloading and Overriding in PHP -


https://www.geeksforgeeks.org/function-overloading-and-overriding-in-php/

What is the meaning of a final class and a final method?

The final class is a class that cannot be extended by other classes - final Class
className

final function functionName(Parameter1, Parameter2, ...);

PHP final class is a class which prevents overriding a method of the child classes
just by the final prefix with the definition. It means that if we are defining a
method with the final prefix then it is going to prevent overriding the method

final method: A method is considered a final method if it is prefixed with the


final keyword. The final methods are the methods that cannot be overridden. So,
these methods can’t be overridden in child/subclasses. It increases security by
preventing the modification of functions

--------- MySQL ---------

InnoDB is the default database engine used in MySQL 5.5 and later

Difference between InnoDB & MyISAM

What is the difference between CHAR and VARCHAR?

What is the difference between UNIX timestamps and MySQL timestamps? - MySQL
timestamp is represented in the readable format of YYYY-MM-DD HH:MM:SS format

How to display the nth highest salary from a table in a MySQL query? - To find Nth
highest salary is: - select distinct(salary) from employee order by salary desc
limit n-1,1

OFF SET - allows us to specify which row to start from retrieving data

if you want to find 3rd largest salary: - select distinct(salary) from employee
order by salary desc limit 2,1

What is the query to display the top 20 rows - SELECT * FROM table_name LIMIT 0,20;

Write a query to retrieve a hundred books starting from 20th. - SELECT book_title
FROM books LIMIT 20, 100;

What is the usage of ENUMs

What is BLOB and TEXT in MySQL

which are reference_option to maintains the referential integrity between the child
and parent tables - CASCADE,RESTRICT,NO ACTION,SET NULL

How to find the second highest salary in MySQL? - SELECT salary FROM (SELECT salary
FROM employees ORDER BY salary DESC LIMIT 2) AS Emp ORDER BY salary LIMIT 1;

UNION performs a DISTINCT on the result set, eliminating any duplicate rows.

UNION ALL does not remove duplicates, and it therefore faster than UNION.
When GROUP BY is not used, HAVING behaves like a WHERE clause. The difference
between where and having: WHERE filters ROWS while HAVING filters groups

SELECT SUM(spending) as totSpending


FROM militaryspending
HAVING SUM(spending) > 200000;

--------------------- CI -------------------

https://www.interviewbit.com/codeigniter-interview-questions/

Know CI Version - https://www.kodingmadesimple.com/2016/08/find-codeigniter-


version.html

What are the hooks in CodeIgniter? - The Hook is a feature in CodeIgniter that
provides a way to change the inner working of the framework without hacking the
core files/functionality.

hooks are events which can be called before and after the execution of a program

$config['enable_hooks'] = TRUE;

Path : application/config/hooks.php

pre_controller,post_controller

pre_system : It is called much before the system execution. Only benchmark and hook
class have been loaded at this point.

post_system: It is called after the final page is sent to the browser at the end of
the system execution.

What is an inhibitor of CodeIgniter? - an error handler class that uses native PHP
functions like set_exception_handler, set_error_handler, register_shutdown_function
to handle parse errors, exceptions, and fatal errors.

What is a helper in CodeIgniter? How can a helper file be loaded - Each helper
function performs one specific task, with no dependence on other functions

Some helpers:Cookie,CAPTCH Helper,Date Helper,Download Helper,Email Helper,URL


Helper, Form Helper

Explain the CodeIgniter library. How will you load it (Path : system/libraries)

which indirectly increase the speed of developing an application

Session, Benchmarking,Email,Calender Class,Encrypt,File Uploading,Form


Validation,FTP,Language (application/language/english/), Pagination
(create_links()), User Agent, Zip (Write, Download)

Connect Multiple Database:

// use master dataabse


$users = $this->db->get('users');
// connect to secondary database
$otherdb = $this->load->database('otherdb', TRUE);
Difference between CI 2 & CI 3

Classes file names convention (Start with a capital letter)


Session library (Completely re-written. The default file is session now)
New Encryption library
Usage of XSS filtering (Input filtering is wrong)
Active Record is renamed to Query Builder
Composer auto-loader

What is $this in CI

$this actually represents the singleton Codeigniter instance (which is actually the
controller object). For example when you load libraries/models, you're attaching
them to this instance so you can reference them as a property of this instance

--------- Laravel ---------

What is HTTP middleware? - verifies whether the user of the application is


authenticated or not,inspecting and filtering HTTP requests - location :
app/Http/Middleware
SELECT MAX(salary) FROM employees WHERE salary NOT IN ( SELECT Max(salary) FROM
employees);

Explain reverse routing in Laravel. - generating URL's based on route declarations,


Using reverse routing we can create a link - {{ HTML::link_to_action('users@login')
}}

How will you register service providers? - in the config/app.php configuration


file - providers array

default : AppServiceProvider,AuthServiceProvider,EventServiceProvider

How can you enable query log in Laravel? - DB::enableQueryLog();,


DB::getQueryLog();

What does ORM stand for?

List available types of relationships in Laravel Eloquent.

Name the Template Engine utilized by Laravel.

Name databases supported by Laravel. - MariaDB,MySQL,PostgreSQL,SQLite

What is migrations and why it's important? - database/migrations - Migrations are


like version control for your database, useful for schema definition

e.g : php artisan make:migration create_flights_table

How to rollback last migration? - https://laravel.com/docs/9.x/migrations#main-


content

php artisan migrate:rollback --step=1

php artisan make:seeder UserSeeder

How will you check table is exists or in the database? - Schema::hasTable('users'),


Schema::hasColumn('users', 'email')
Define @include and @yield.
@include defines view to inject into parent. @yield defines section to be injected.
@yield works only if your view @extends the parent view.

Explain traits in Laravel - mechanism for code reuse

Define Implicit Controller. - Laravel allows you to easily define a single route to
handle every action in a controller

Route::controller('users', 'UserController', [
'anyLogin' => 'user.login',
]);

Eloquent - it's a ORM (object-relational mapper), used to interact with DB

Laravel throttling - use to accept no. of request comming from browser, by default
it is 10 request per minutes

use Illuminate\Support\Facades\RateLimiter;

What is Bundles ? - packages - usefull to build application faster like


socialite,cashier,

Redis : Redis is an open source, advanced key-value store. It is often referred to


as a data structure server since keys can contain strings, hashes, lists, sets, and
sorted sets.

Before using Redis with Laravel, we encourage you to install and use the phpredis
PHP extension via PECL

What is an Observer? - group all of your listeners into a single class

listeners

events in Laravel. = App\Providers\EventServiceProvider

php artisan make:observer UserObserver --model=User , app/Events , app/Listeners

Explain the concept of contracts in Laravel. - a set of interfaces that define the
core services provided by the framework e.g. Queue contract, Mailer contract

Where will you define Laravel's Facades? - a facade is a class that provides access
to an object from the service container

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

Route::get('/cache', function () {
return Cache::get('key');
});

Helper functions

use Illuminate\Support\Facades\Response;
Route::get('/users', function () {
return response()->json([
// ...
]);
});
Service Container - powerful tool for managing class dependencie

authentication involves checking the validity of the user credentials,


and authorization involves checking the rights and permissions over the resources
that an authenticated user has

Mutators and Accessor

https://stackoverflow.com/questions/49969855/what-are-mutators-and-accessors-in-
laravel

https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor

broadcasting - websocket - we can use pusher JS

Eager Loading

https://medium.com/@sdkcodes/laravel-eloquent-eager-loading-9596b15e8b5d

Gate : Gates are simply closures that determine if a user is authorized to perform
a given action. Typically, gates are defined within the boot method of the App\
Providers\AuthServiceProvider

https://laravel.com/docs/9.x/authorization#gates

php artisan queue:retry

php artisan make:job ProcessPodcast

php artisan schedule:list

Defining Schedules - inside App\Console\Kernel

Use Queue Jobs

use App\Jobs\Heartbeat;

$schedule->job(new Heartbeat)->everyFiveMinutes();

Collection : https://stackoverflow.com/questions/41466295/what-is-a-laravel-
collection - Useful for Array processing

$array=[
["id"=>1,"name"=>"Apple"],
["id"=>2,"name"=>"Banana"],
["id"=>1,"name"=>"Apple"],
["id"=>2,"name"=>"Banana"],
];

$result= collect($array)->unique("id");

Laravel Telescope makes a wonderful companion to your local Laravel development


environment. Telescope provides insight into the requests coming into your
application, exceptions, log entries, database queries, queued jobs, mail,
notifications, cache operations, scheduled tasks, variable dumps, and more

php artisan make:model Todo -mcr


php artisan make:model Todo -a - -a, --all Generate a migration, factory, and
resource controller for the model

factories are classes that extend Laravel's base factory class and define a
definition method.

example : Via the fake helper, factories have access to the Faker PHP library

------------------------- jQuery ----------------------------

Can you use any other name in place of $ (dollar sign) in jQuery?

What are the effects methods used in jQuery?

What is the use of toggle() method in JQuery?

What is the use of html() method in JQuery?

Is jQuery library used for server scripting or client scripting?

Can you use multiple document.ready() function on the same page?

What is the difference between find and children methods?

What are the selectors in jQuery? - Name,ID,Classs,

What is a use of jQuery filter? - This method lets you specify a criteria

What is the use of serialize() method in JQuery? - creates a URL encoded text
string by serializing form values

How to add and remove CSS classes to an element using jQuery?

What is the use of the animate() method in jQuery?

What is a CDN?

$.ajax(... async: false ...); // Hey browser! first complete this request, then go
for other codes

What is jQuery? - jQuery is a fast, small, and feature-rich JavaScript library

What is the difference between JavaScript and jQuery?

JavaScript is an independent language and can exist on its own, jQuery is a


JavaScript library

JavaScript uses JIT[Just in Time Compiler] which is a combination of interpreter


and Compile and is written in C. It’s a combination of ECMA script and DOM
(Document Object Model).

JavaScript uses long lines of code as an individual has to write the code own-
self.beha

In JavaScript, we have to write extra code or move around to have cross-browser


compatibility.

JavaScript is a language, obviously, it would be heavier than JQuery.


We can make animations in JavaScript with many lines of code. Animations are mainly
done by manipulating the style of an Html page

JavaScript is a programming language.

---------

While JQuery Uses the resources that are provided by JavaScript to make things
easier. It is a lightweight JavaScript library. It has only the DOM

With JQuery, one has to write fewer lines of code than JavaScript. We just need to
import the library and use the only specific functions or methods of the library in
our code.

JQuery has an inbuilt feature of cross-browser compatibility. We don’t need to


worry about writing extra lines of code or moving around in order to make our code
compatible with any browser.

While JQuery is a library, derived from JavaScript hence, it is lightweight.

In JQuery, we can add animation effects easily with fewer lines of code.

jQuery is an Application Programming Interface (API).

----------------- Git Useful Commands ---------------

https://www.freecodecamp.org/news/10-important-git-commands-that-every-developer-
should-know/

------ PHP Technical Task -----

https://www.w3resource.com/php-exercises/php-math-exercise-1.php

find the maximum and minimum marks from the following set of arrays.

$marks1 = array(360,310,310,330,313,375,456,111,256);
$marks2 = array(350,340,356,330,321);
$marks3 = array(630,340,570,635,434,255,298);

Desired Output:

Maximum marks : 635


Minimum marks : 111

reverse a string without predefined function - strrev()

// consider string
$string = 'Hello Dhanraj, Good Evening.';

echo "Entered String: " . $string . "<br />";


// find string length
$str_len = strlen($string);

echo "Reversed String: ";


// loop through it and print it turn around
for ( $x = $str_len - 1; $x >=0; $x-- )
{
echo $string[$x];
}

------------- Laravel Coding related exercise --------

https://chat.openai.com/c/b325343b-b03c-433a-af38-44a77dfe0313

Task: How can I logs the user activity using middleware, and how can I by pass some
route

https://chat.openai.com/c/b325343b-b03c-433a-af38-44a77dfe0313

other:

// Eloquent code to retrieve users ordered by latest post (excluding users with no
posts)
$users = User::has('posts')->with(['posts' => function ($query) {
$query->latest();
}])->get();

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

You might also like