Home  • Framework • Laravel

Laravel Question & answer

IDB-BISEW

1. What is Laravel

Ans: Laravel is free open source “PHP framewok” based on MVC Design Pattern. It is created by Taylor Otwell. Laravel provides expressive and elegant syntax that helps in creating a wonderful web application easily and quickly.

2. What is Lumen?

Ans: Lumen is PHP micro framework that built on Laravel’s top components. It is created by Taylor Otwell.It is the perfect option for building Laravel based micro-services and fast REST API’s. It’s one of the fastest micro-frameworks available

3. List out some benefits of Laravel over other Php frameworks ?

Ans: Top benifits of laravel framework: i. Setup and customization process is easy and fast as compared to others. ii. Inbuilt Authentication System. iii. Supports multiple file systems iv. Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir,Passport,Laravel Scout. v. Eloquent ORM (Object Relation Mapping) with PHP active record implementation. vi. Built in command line tool “Artisan” for creating a code skeleton ,database structure and build their migration.

4. List out some latest features of Laravel Framework.

i. Inbuilt CRSF (cross-site request forgery ) Protection. ii. Inbuilt paginations iii. Reverse Routing iv. Query builder v. Route caching vi. Database Migration vii. IOC (Inverse of Control) Container Or service container

5. What is composer ?

Ans: Composer is PHP dependency manager used for installing dependencies of PHP applications. It provides us a nice way to reuse any kind of code. Rather than all of us reinventing the wheel over and over, we can instead download popular packages.

6. How to install Laravel via composer ?

Ans: To install Laravel with composer run below command on your terminal. composer create-project Laravel/Laravel your-project-name version

7. What is php artisan. List out some artisan commands ?

Ans: 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: a) php artisan list <img src="/images/emotions/facebook_emotions/fbglasses.png" title="Glasses" alt="Glasses" /> php artisan help c) php artisan tinker d) php artisan make e) php artisan –version f) php artisan make model model_name g) php artisan make controller controller_name

8. List some Aggregates methods provided by query builder in Laravel ?

Ans: Aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurements such as a set, a bag or a list Below is list of some Aggregates methods provided by Laravel query builder. • count() Usage<img src="/images/emotions/hotmail_emotions/red_smile.gif" title="Embarrassed" alt="Embarrassed" />products = DB::table(‘products’)->count(); • ma<img src="/images/emotions/yahoo_emotions/14.gif" title="Angry" alt="Angry" />) Usage<img src="/images/emotions/hotmail_emotions/red_smile.gif" title="Embarrassed" alt="Embarrassed" />price = DB::table(‘orders’)->ma<img src="/images/emotions/yahoo_emotions/14.gif" title="Angry" alt="Angry" />‘price’); • min() Usage<img src="/images/emotions/hotmail_emotions/red_smile.gif" title="Embarrassed" alt="Embarrassed" />price = DB::table(‘orders’)->min(‘price’); • avg() Usage<img src="/images/emotions/hotmail_emotions/red_smile.gif" title="Embarrassed" alt="Embarrassed" />price = DB::table(‘orders’)->avg(‘price’); • sum() Usage: $price = DB::table(‘orders’)->sum(‘price’);

9. What happens when you type “php artisan” in the command line?

Ans: When you type “PHP artisan” it lists of a few dozen different command options.

10. Which template engine Laravel use ?

Ans: Laravel uses Blade Templating Engine. 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. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.

11. How can you change your default database type ?

Ans: By default Laravel is configured to use MySQL.In order to change your default database edit your config/database.php and search for ‘default’ => ‘mysql’ and change it to whatever you want (like ‘default’ => ‘sqlite’).

12. Explain Migrations in Laravel ? How can you generate migration .

Ans: what are laravel migrations Laravel 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. Steps to Generate Migrations in Laravel • To create a migration, use the make:migration Artisan command • When you create a migration file, Laravel stores it in /database/migrations directory. • Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations. • Open the command prompt or terminal depending on your operating system.

13. What are service providers in laravel ?

Ans: 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. Service provider basically registers event listeners, middleware, routes to Laravel’s service container. All service providers need to be registered in providers array of app/config.php file.

14. How do you register a Service Provider?

Ans: To register a service provider follow below steps • Open to config/app.php • Find ‘providers’ array of the various ServiceProviders. • Add namespace ‘IluminateAbcABCServiceProvider:: class,’ to the end of the array.

15. What are Implicit Controllers ?

Ans: Implicit Controllers allow you to define a single route to handle every action in the controller. You can define it in route.php file with Route: controller method. Usage : Route::controller('base URI','');

16. Explain Laravel service container ?

Ans: One of the most powerful feature of Laravel is its Service Container . It is a powerful tool for resolving class dependencies and performing dependency injection in Laravel. Dependency injection is a fancy phrase that essentially means class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.

17. How to enable query log in Laravel?

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

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

Ans: You can use request’s class ip() method to get IP address of user in Laravel. Usage: public function getUserIp(Request $request){ // Getting ip address of remote user return $user_ip_address=$request->ip(); }

19. What are Laravel Facades ?

Laravel Facades provides a static like interface to classes that are available in the application’s service container. Laravel self ships with many facades which provide access to almost all features of Laravel’s. Laravel Facades serve as “static proxies” to underlying classes in the service container and provides benefits of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods of classes. All of Laravel’s facades are defined in the IlluminateSupportFacades namespace. You can easily access a Facade like so: use IlluminateSupportFacadesCache; Route::get('/cache', function () { return Cache::get('key'); });

20. How to use custom table in Laravel Model ?

Ans: We can use custom table in Laravel by overriding protected $table property of Eloquent. Below is sample uses class User extends Eloquent{ protected $table="my_custom_table"; }

21. How can you define Fillable Attribute in a Laravel Model ?

Ans: We can define fillable attribute by overiding the fillable property of Laravel Eloquent. Here is sample uses Class User extends Eloquent{ protected $fillable =array('id','first_name','last_name','age'); }

22. What is the purpose of the Eloquent cursor() method in Laravel ?

Ans: 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 foreach (Product::where('name', 'bar')->cursor() as $flight) { //do some stuff }

23. What are Closures in laravel ?

Ans: Closures are 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.

24. What is Kept in vendor directory of Laravel ?

Ans: Any packages that are pulled from composer is kept in vendor directory of Laravel.

25. What are Laravel Contracts ?

Ans: Laravel’s Contracts are nothing but set of interfaces that define the core services provided by the Laravelframework.

26. What does PHP compact function do ?

Ans: compact() laravel PHP compact function takes each key and tries to find a variable with that same name.If the variable is found, them it builds an associative array.

27. In which directory controllers are located in Laravel ?

Ans: We kept all controllers in App/Http/Controllers directory

28. Define ORM ?

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

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

Ans: 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. public function saveProduct(Request $request ) $product = new product; $product->name = $request->name; $product->description = $request->name; $product->save();

30. How to get Logged in user info in Laravel ?

Ans: Auth::User() function is used to get Logged in user info in Laravel. Usage:- if(Auth::check()){ $loggedIn_user=Auth::User(); dd($loggedIn_user); }

31. Does Laravel support caching?

Ans: Yes, Laravel supports popular caching backends like Memcached and Redis. By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the file system .For large projects it is recommended to use Memcached or Redis.

32. What are traits in Laravel ?

Ans: what are laravel traits Laravel Traits are simply a group of methods that you want include within another class. A Trait, like an abstract classes cannot be instantiated by itself.Trait are created to reduce the limitations of single inheritance in PHP by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. Here is an example of trait. trait Sharable { public function share($item) { return 'share this item'; } } You could then include this Trait within other classes like this: class Post { use Sharable; } class Comment { use Sharable; } Now if you were to create new objects out of these classes you would find that they both have the share() method available: $post = new Post; echo $post->share(''); // 'share this item' $comment = new Comment; echo $comment->share(''); // 'share this item'

33. How to create migration via artisan ?

Ans: Use below commands to create migration data via artisan. // creating Migration php artisan make:migration create_users_table

34. Explain validations in laravel?

Ans: In Programming validations are a handy way to ensure that your data is always in a clean and expected format before it gets into your database. Laravel provides several different ways to validate your application incoming data.By default Laravel’s base controller class uses a ValidatesRequests trait which provides a convenient method to validate all incoming HTTP requests coming from client.You can also validate data in laravel by creating Form Request.

35. Explain Laravel Eloquent.

Ans: Laravel’s Eloquent ORM is one the most popular PHP ORM (OBJECT RELATIONSHIP MAPPING). It provides a beautiful, simple ActiveRecord implementation to work with your database. In Eloquent each database table has the corresponding MODEL that is used to interact with table and perform a database related operation on the table. Sample Model Class in Laravel. namespace App; use IlluminateDatabaseEloquentModel; class Users extends Model { }

36. Define Active Record Implementation. How to use it Laravel ?

Ans: Active Record Implementation is an architectural pattern found in software engineering that stores in-memory object data in relational databases. Active Record facilitates the creation and use of business objects whose data is required to persistent in the database. Laravel implements Active Records by Eloquent ORM. Below is sample usage of Active Records Implementation is Laravel. $product = new Product; $product->title = 'Iphone 6s'; $product->save(); Active Record style ORMs map an object to a database row. In the above example, we would be mapping the Product object to a row in the products table of database.

37. List Types of relationships supported by Laravel ?

Ans: Laravel support 7 types of table relationships, they are • One To One • One To Many • One To Many (Inverse) • Many To Many • Has Many Through • Polymorphic Relations • Many To Many Polymorphic Relations

38. Explain Laravel Query Builder ?

Ans|: Laravel’s database query builder provides a suitable, easy interface to creating and organization database queries. It can be used to achieve most database operations in our application and works on all supported database systems. The Laravel query planner uses PDO restriction necessary to keep our application against SQL injection attacks.

39. What is Laravel Elixir ?

Ans: Laravel Elixir provides a clean, fluent API for defining basic Gulp tasks for your Laravel application. Elixir supports common CSS and JavaScript preprocessors like Sass and Webpack. Using method chaining, Elixir allows you to fluently define your asset pipeline.

40. List out Databases Laravel supports ?

Ans: Currently Laravel supports four major databases, they are :- • MySQL • Postgres • SQLite • SQL Server

41. How to get current environment in Laravel 5 ?

Ans: You may access the current application environment via the environment method. $environment = App::environment(); dd($environment);

42. What is the purpose of using dd() function iin laravel ?

Ans: Laravel’s dd() is a helper function ,which will dump a variable’s contents to the browser and halt further script execution.

43. What is Method Spoofing in Laravel ?

Ans: As HTML forms does not supports PUT, PATCH or DELETE request. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method: <form action="/foo/bar" method="POST"> <input type="hidden" name="_method" value="PUT"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> </form> To generate the hidden input field _method, you may also use the method_field helper function: <?php echo method_field('PUT'); ?> In Blade template you can write it as below {{ method_field('PUT') }}

44.What is middleware in laraval? How to assign multiple middleware to Laravel route ?

Ans: Middleware provide a convenient mechanism for filtering HTTP requests entering the application. We can assign multiple middleware to Laravel route by using middleware method. Example // Assign multiple multiple middleware to Laravel to specific route Route::get('/', function () { // })->middleware('firstMiddleware', 'secondMiddleware'); // Assign multiple multiple middleware to Laravel to route groups Route::group(['middleware' => ['firstMiddleware','secondMiddleware']], function () { // });

45. How can you display HTML with Blade in laravel?

Ans: To display html in laravel you can use below synatax. {!! $your_var !!}

46. What is route in laraval?

Ans: Route is a way of creating a request URL of your application. These URL do not have to map to specific files on a website. The best thing about these URL is that they are both human readable and SEO friendly. Laravel offers the following route methods: (get,post,put,delete,patch,option)

47. What is pivot table in laravel?

Ans: Laravel Daily has a new post on pivot tables and many-to-many relationships: ... Apivot table is an example of intermediate table with relationships between two other “main” tables.

48. Briefly Describe @yield, @extends and @section.

Ans: @yield: @yield is a section which requires to be filled in by your view which extends the layout. You could pass it a default value through the second parameter if you'd like. Usages for @yield could be the main content on your page. @section<img src="/images/emotions/hotmail_emotions/angry_smile.gif" title="Angry" alt="Angry" />section is a section which can contain a default value which you can override or append to. Think of usages for @section as a sidebar, a widget section, etc.

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd