Showing posts with label PHP Frameworks. Show all posts
Showing posts with label PHP Frameworks. Show all posts

Wednesday, May 3, 2017

Top Laravel Interview Questions with Answers

Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites. Laravel helps you create applications using simple, expressive syntax. Now a days Laravel is very popular PHP framework so mostly companies works on this framework. Here we are listing top Laravel interview questions with answers.



1. What is Laravel?
Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites. Laravel helps you create applications using simple, expressive syntax.

2. What are Advantages of Laravel?

  • Easy and consistent syntax
  • Set-up process is easy
  • customization process is easy
  • code is always regimented with Laravel
3. Explain about Laravel Project?
Laravel is one of the most popular PHP frameworks used for Web Development.
This framework is with expressive, elegant syntax.
It is based on model–view–controller (MVC) architectural pattern.

4. What are the feature of Laravel 5.4?
  • Introducing Laravel Dusk
  • Introducing Laravel Mix 
  • New Markdown Mail in Laravel 5.4 
  • Slots and Components in Laravel 5.4
  • Real-time (automatic) Facades in Laravel 5.4
  • TrimStrings and ConvertEmptyStringsToNull middleware in Laravel 5.4
  • JSON localization files in Laravel 5.4
  • Binding method calls in the service container in Laravel 5.4 
  • The --model flag for creating better resourceful controllers in Laravel 5.4
  • Laravel Collections' updates--higher order messaging and new methods--in Laravel 5.4 
5. Compare Laravel with Codeigniter?
        Laravel                                                                                        Codeigniter
Laravel is a framework with expressive, CodeIgniter is a powerful PHP                       elegant syntax                                                                    framework
Development is enjoyable, creative                                 Simple and elegant toolkit to create full-         experience                                                                         featured web applications.
Laravel is built for latest version of PHP                         Codeigniter is an older more mature                                                                                                         framework
It is more object oriented compared                                 It is less object oriented compared to               to CodeIgniter.                                                                  Laravel.
Laravel community is still small, but it is                        Codeigniter community is large.
growing very fast.

6. What are Bundles,Reverse Routing and The IoC container ?

Bundles: These are small functionality which you may download to add to your web application.
Reverse Routing: This allows you to change your routes and application will update all of the relevant links as per this link.
IoC container: It gives you Control gives you a method for generating new objects and optionally instantiating and referencing singletons.

Also Read: PHP Interview Questions with Answers

7. How to set Database connection in Laravel?
Database configuration file path is : config/database.php
Following are sample of database file

[code]  'mysql' => [
    'read' => [
        'host' => 'localhost',
    ],
    'write' => [
        'host' => 'localhost'
    ],
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
], [/code]

8. How to enable the Query Logging?
[code] DB::connection()->enableQueryLog();[/code]

9. How to use select query in Laravel?
[code] $users = DB::select('select * from users where city_id = ?', 10);
if(!empty($users)){
    foreach($users as $user){

    }
} [/code]

9. How to use Insert Statement in Laravel?
[code] DB::insert('insert into users (id, name, city_id) values (?, ?)', [1, 'Web technology',10]); [/code]

10. How to use Update Statement in Laravel?
[code]  DB::update('update users set city_id = 10 where id = ?', [1015]); [/code]

11. How to use Update Statement in Laravel?
[code]  DB::update('update users set city_id = 10 where id = ?', [1015]);[/code]

12. How to use delete Statement in Laravel?
[code] DB::delete('delete from  users where id = ?', [1015]); [/code]

13. Does Laravel support caching?
Yes, Its provides.

Also Read: Top Zend Framework Interview Questions with Answers

14. I've already created a database table that I want to use with Laravel's ORM. How would I setup a class to do that?
Laravel's ORM is called Eloquent. There are two main ways to go about doing this. The first one would be to physically write a class:
[code] <?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'students';
}[/code]

And the second one would be to use the artisan CLI, which generates a class:
[code] php artisan make:model students [/code]

15. Laravel comes with a PHP CLI called artisan. What is your favorite artisan command?
There are so many things that the CLI does out of the box. Even if they don't have a favorite command, they should be able to explain what some of them do. Here's a sample of available top-level commands:
Available commands:
  •   clear-compiled      Remove the compiled class file
  •   down                Put the application into maintenance mode
  •   env                 Display the current framework environment
  •   help                Displays help for a command
  •   inspire             Display an inspiring quote
  •   list                Lists commands
  •   migrate             Run the database migrations
  •   optimize            Optimize the framework for better performance
  •   serve               Serve the application on the PHP development server
  •   tinker              Interact with your application
  •   up                  Bring the application out of maintenance mode
16. Laravel 5 has built in CSRF protection on every route. How would I go about turning that off?
  Hopefully they mention that CSRF protection is important, but since we're asking them to turn it off they might not mention it which is OK. You'd easily turn it off by going into Kernel.php and removing it from the middleware stack that is ran on every route.

This is also a good place to ask about middleware in general and make sure they both understand what middleware is and why it's important.

17. List out some benefits of Laravel over other Php frameworks.
  • Setup and customization process is  easy and fast as compared to others.
  • Inbuilt Authentication System.
  • Supports multiple file systems
  • Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir,Passport,Laravel Scout.
  • Eloquent ORM (Object Relation Mapping) with PHP active record implementation. 
  • Built in command line tool “Artisan” for creating a code skeleton ,database structure and build their migration.
Also Read: WordPress Interview Questions And Answers

18. What is composer ?
Composer is PHP dependency manager used for installing dependencies of PHP applications.

19. How to install laravel via composer ?

 composer create-project laravel/laravel your-project-name version

 20. How to check laravel current version ?
 You can check the current version of your Laravel installation using the --version option of artisan command Usages:
 [code] php artisan --version [/code]

21. What is php artisan. List out some artisan command ?

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. Here are the list of some artisian command:
  • php artisan list
  • php artisan help
  • php artisan tinker
  • php artisan make
  • php artisan --versian
  • php artisan make modal modal_name
  • php artisan make controller controller_name 
22. Explain Events in laravel ?

An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation,that allow us  to subscribe and listen for events in our application.
Below are some events examples in laravel :
A new user has registered
A new comment is posted
User login/logout
New product is added.

23. How to enable query log in laravel?

Use the enableQueryLog method:
DB::connection()->enableQueryLog();
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();

Also Read: Most Popular Codeigniter Interview Questions with Answers

24. How to turn off CRSF protection for a route in Laravel?

In "app/Http/Middleware/VerifyCsrfToken.php"
 //add an array of Routes to skip CSRF check
  private $exceptUrls = ['controller/route1', 'controller/route2'];
 //modify this function

[code]public function handle($request, Closure $next) {
 //add this condition foreach($this->exceptUrls as $route) {
 if ($request->is($route)) {
  return $next($request);
 }
}
return parent::handle($request, $next);
}[/code]

25. How can you get users IP address  in Laravel ?

[code] public function getUserIp(Request $request){
          // Getting ip address of remote user

            return $user_ip_address=$request->ip();
}[/code]

26. How to use custom table in Laravel Modal We can use custom table in laravel by overriding protected $table property of Eloquent. Below is sample uses

[code] class User extends Eloquent{
 protected $table="my_user_table";

}[/code]

27. How to define Fillable Attribute in Laravel Modal ?
You can define fillable attribute by overiding the fillable property of Laravel Eloquent. Here is sample uses

[code] Class User extends Eloquent{

protected $fillable =array('id','first_name','last_name','age');


}[/code]

28. In which directory controllers are located in Laravel ?

We kept all controllers in
app/http/Controllers directory

29. What does PHP compact function do ?
PHP compact function takes each key and tries to find a variable with that same name.If variable is found , them it builds an associative array.

30. Define ORM ?
Object-relational Mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages.

Also Read: Apache Solr Interview Questions and Answers

31. How to create a record in Laravel using eloquent? 

To create a new record in the database using laravel Eloquent, simply create a new model instance, set attributes on the model, then call the save method: Here is sample Usage

[code] public function saveProduct(Request $request )
 $product = new product;
 $product->name = $request->name;
 $product->description = $request->name;
 $product->save(); [/code]

 32. What is the purpose of the Eloquent cursor() method in laravel?

The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage. Example Usage

[code] foreach (Product::where('name', 'bar')->cursor() as $flight) { //do some stuff } [/code]

33. How to get Logged in user info in laravel ?

Auth::User() function is used to get Logged in user info in laravel. Usage:

[code] if(Auth::check()){

$loggedIn_user=Auth::User();
dd($loggedIn_user);

} [/code]


34. What are Closures in laravel ?
Closures is an anonymous function that can be assigned to a variable or passed to another function as an argument.A Closures can access variables outside the scope that it was created.


Sunday, May 1, 2016

The Best PHP Framework for Web Development

Before start with frameworks, I assume that you have worked in core PHP. Everyone knows that in Core PHP you have to write and manage lot code. You must care about the Session, Routing, Authentication and other stuff that will make your code more complex and complicated.
A framework is something which provides a lot of functionality which is already written, tested and ready to use. There are lots of pre-build libraries for the session, form-validation, url, authentication in a framework which you don’t need to write again and save your lot time. The framework is faster, because it allows developers to save time by re-using generic modules in order to focus on other areas. Here is a collection of best and most famous PHP frameworks based on their functionality and popularity. Normally, all frameworks follow the MVC rules. Here MVC stands for MODEL, VIEW and CONTROLLER which is standard software development process.

There are several frameworks that could be used as a quick RAD (Rapid Application Development) tools.

Codeigniter

If you're a web developer who's in need of a simple and an elegant toolkit for creating feature-loaded and visualling impressive web applications, then Codeigniter is the framework for you. Currently available in its version 2.2.1, Codeigniter comes with clear documentation. Some other interesting features of this PHP framework include: nearly zero configuration, no large-scale monolithic libraries, compatibility with standard hosting, no restrictive coding rules, no need for template language and many more.


Pros
  • It is a frame work which offers developers simple set up options. Even a beginner finds this platform ideal for setting a task.
  • Highly illustrated documentation.
  • Superb speed, no lags.
  • Like CakePHP, Codelgniter has massive community support.
Cons
  • The library is not so exhaustive or refined as in other platforms.
  • Lack of default modular separation of codes.
  • It is difficult to maintain or modify codes.

CakePHP

Considered as a contemporary framework for PHP development, CakePHP 3.0 comes loaded with remarkable features including enhanced components and helpers, improved session management, improved consistency of conventions, ORM improvements and many more. CakePHP 3.0 comes with increased modularity, allowing you to create more standalone libraries in addition to reducing coupling. Plus, there are tools like PSR-0, PSR-1 and composer which have helped in improving the interoperability.

Pros
  • Great community support which can clear any queries about website development in an effective way.
  • Very useful ORM which helps developers to create excellent queries as well as codes.
  • Availability of fantastic plugins to keep the codes clean as well as elegant. 
Cons
  • Bulky codes. When we compare CakePHP with other frameworks the codes for doing a particular task look huge.
  • It is one of the slowest performing platforms.
  • The loading of codes, even though auto loading options work in a minimum pace.

 Symfony 2 

 Available in its version 2, Symfony is an excellent PHP Framework for creating websites and web applications. It has been built on top of Symfony components such as Drupal, Ez Publish and phpBB. With over 300,000 developers on-board, Symfony has witnessed over 1,000,000 downloads till date. There have been more than 1000 code contributors for Symfony till date. Backed by a huge community of Symfony fans, it is believed that the framework will go to a whole new level in the forthcoming years.


 Pros
  • Flexibility in setting up projects.
  • Developers get the option of choosing their own ORM
  • Symphony components can be incorporated to much bigger projects like Drupal.

Cons
  • Documentation lacks ample references.
  • The security mechanism of symfony is hard to use.
  • File parsing in symfony is a bit difficult task.

 Yii Framework

 Considered as a fast, stable, secure and high-performing PHP framework, Yii has worked wonders for developing Web 2.0 applications. It provides the basis and advanced application installations based on the project requirement. Equipped with Model-View-Controller(MVC) design pattern, rich feature layered caching scheme, Role based access and authentication, Database Access Objects(DAO), Ajax-enabled widgets and a detailed documents; Yii serves as an ideal framework for developing enterprise web applications, social media applications, SaaS, PaaS and a lot more.

Pros
  • For doing tasks such as search, pagination, and Grids developers can resort to built-in Ajax.
  • Light- weighted codes.
  • Superb security, and great extensions.
  • Very easy framework to learn.

Cons


  • It lacks the support of much needed extensions to create complex applications.
  • The availability of experts is not high in number when we compare Yii2 with other platforms.
  • The community support is not so massive as developers get for CakePHP.

 Zend Framework

Considered as one of the most popular PHP Frameworks for building high performing web applications, Zend comes with cryptographic and secure coding tools which allow you to execute web app development projects in a flawless manner. Some interesting features of Zend framework include: modularity, extensibility, enterprise ready and a vibrant community.



Pros 
  • It's very robust, well tested and very widely used.
  • One of the oldest and most trusted frameworks of PHP.
  • It has all the features that a good Web Framework should have.
Cons
  • Too much bloatware.
  • It's really slow compared to other frameworks like Laravel (Voted the best PHP framework for many years now).
  • Documentation is pretty bad. For a newbie, its really hard to understand how things work.



FuelPHP

FuelPHP is a simple and highly flexible MVC(Model View Control) framework specially created for PHP web developers. Irrespective of whether you’re an experienced PHP developer or an amateur; using FuelPHP framework can turn to be your best decision. PHPFuel supports a router-based approach. That means, you are directly navigated to a closure which deals with input uri, offering the closure a complete control over any further execution.



Pros
  •  One of the many benefits of Fuel is that there are very few restrictions on how to write code. 
  •  Just like CodeIgniter framework, FuelPHP is huge community driven framework used for web development.
  •  Fuel doesn't force anyone into using modules or an HMVC file structure, but if one chooses to implement them the process is well documented and quite easy to integrate. Once apps are created in a modular structure fashion, it becomes easier for developers with clear benefits.
  •  This framework supports input filtering, CSRF prevention with tokens and the Query Builder which assists in preventing any SQL injection attacks. 
Cons
  •  Might be a bit too much to understand for a beginner to intermediate Codeigniter user or PHP developer due to how the file system is laid out.
  •  It’s still a relatively new framework which could have caveats that have yet to rear their heads. Although, I encountered no problems when I used it.
  •  Documentation is still sparse, a lot of sections are still incomplete.
  •  The community is rather small and there aren’t really many applications built with it you can learn convention from


Phalcon

Considered as one of the fastest PHP Frameworks, Phalcon has been implemented as a C extension coupled with lower resource consumption. Some of the excellent features included within this PHP Framework are: translations, security, assets management, universal auto-loader and many more. You can use Phalcon for developing full MVC applications viz: single-module, multi-module and micro applications.


Pro
  • Fastest RETful micro framework available
  • Speed alone places it in whole separate category
  • Extremely optimized and modular, use only what you need or want
  • Excellent documentation, unfortunately not that much 3rd party community support, at lease compared to Silex and Slim. But don’t let this discourage you, you will still find more than enough information.
  • C-language based ORM, especially important if you are creating DB oriented application

Cons
  • Nothing special. It doesn’t have such a great vibe like Silex or Slim


 Laravel

Laravel is yet another brilliant PHP Framework that’s equipped with tons of interesting features including RESTful routing, native PHP or light weight tempting engine and many more. Built using several Symfony components, Laravel offers you web application an amazing foundation of reliable and well-tested code. Some other interesting features of Laravel include: a powerful queue library, an amazing ORM, painless routing and a simple authentication.


Pros
  • Really lean and fast.
  • It uses a blade template engine to speed up compiling tasks, and users can include latest features so easily.
  • "Bundled modularity" enables code reusing without much hassles.
  • Best in the class ORM which is easy to understand, hence creation of database relations appears so simple.
  • An outstanding Artisan CLI comprising advanced tools to do tasks, and migrations.
  • Splendid documentation, and an added feature of reverse routing.

Cons
  • It is quite slow, and a new platform for most of the developers to deal with.
  • Amateur developers face problems while extending codes and classes.
  • Community support is not wide in comparison with other platforms.
  • Many methods included in the reverse routing are complex.

Conclusion: Laravel is currently my framework of choice. Its coding style meshes the best with my own which makes developing much quicker for me.

Laravel vs CodeIgniter vs Yii vs Cakephp vs Zend Comparison Chart





Why Laravel is so popular ? List of Laravel features as below:

Authentication : Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box. The authentication configuration file is located at config/auth.php, which contains several well documented options for tweaking the behavior of the authentication services.

Routing system: Laravel comes with an easy-to-use approach to routing. The route can be triggered on the application with good flexibility and control. To match the URI, a directory is created.

Unit-testing : Laravel is built with testing in mind. In fact, support for testing with PHPUnit is included out of the box, and a phpunit.xml file is already setup for your application. The framework also ships with convenient helper methods allowing you to expressively test your applications.

Database: Migrations and Seeding : Migrations are like version control for your database, allowing a team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema. Laravel includes a simple method of seeding your database with test data using seed classes. It is an automated process. Database tables can be seeded with default data which can be utilized for application testing or for initial application setup. Laravel is a breath of fresh air. Keep everyone in sync using Laravel's database agnostic migrations andschema builder.

Eloquent ORM : The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

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

Homestead : Laravel strives to make the entire PHP development experience delightful, including your local development environment. Vagrant provides a simple, elegant way to manage and provision Virtual Machines. Laravel Homestead is an official, pre-packaged Vagrant "box" that provides you a wonderful development environment without requiring you to install PHP, HHVM, a web server, and any other server software on your local machine. No more worrying about messing up your operating system! Vagrant boxes are completely disposable. If something goes wrong, you can destroy and re-create the box in minutes!

HTTP Middleware : HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application.
Support Blade Templates : Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. All Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application.

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

Caching : Laravel provides a unified API for various caching systems. Laravel supports popular caching backends like Memcached and Redis out of the box.
Filesystem / Cloud Storage : Laravel Flysystem integration provides simple to use drivers for working with local filesystems, Amazon S3, and Rackspace Cloud Storage. Even better, it's amazingly simple to switch between these storage options as the API remains the same for each system.
Queue : The Laravel queue service provides a unified API across a variety of different queue back-ends. Queues allow you to defer the processing of a time consuming task, such as sending an e-mail, until a later time which drastically speeds up web requests to your application.

  •  Very well Documented
  •  Class auto loading
  •  Easy to work and begin
  •  MVC is very flexible
  •  Fluent syntax
  •  Modularity
  •  It is an Open Source

Laravel is the most famous as it helps to develop a website using a simple and a clean code in a short time. This web application framework has elegant and expressive syntax. Tasks in the web projects such as authentication, routing, sessions, queuing and caching are made easier.

When compared with other frameworks like codeigniter, Laravel has detailed stack trace. Authorization library, widgets with assets like CSS and JS also form part of this futuristic framework. Libraries and models can be used easily because of the fact that Laravel has Object Oriented Libraries supported with auto complete feature.

Future of Laravel Having proved its dominance amongst the PHP frameworks, the future of Laravel is bright enough. Many more developers will switch over to Laravel in the coming future. Given the frameworks numerous features and benefits of using them, Laravel will no doubt continues to be a choice for developers.