21st Dec, 2019
20
PHP Frameworks
Sharad Jaiswal
Laravel is a web application that eases out the common tasks used in the routing, authentication, caching and sessions with elegant and expressive syntax. Laravel makes the task of development simple without giving up application functionality. It is a PHP framework that follows the Model-View-Controller (MVC) pattern. Eloquent ORM, super-fast mechanism for authentication, blade templating, and superior routing and controllers are some of the best features of Laravel.
Inversion of Control (IoC) or service container is the most important rule to manage the class dependencies in Laravel. Laravel is a compilation of components to compose a modular application and cache all the data from view to the routes.
Below are few major features of Laravel
Q1. What is Laravel?
Laravel is a open-source PHP framework, which is very easy to understand. Taylor Otwell is developer of laravel, it is released on june 2011. Laravel uses existing elements of contrasting frameworks.
The source code of Laravel is hosted on the GitHub and licensed under the terms of MIT License. It has wide range of functionalities including PHP framework like Codelgniter, Yii and other languages like Ruby on Rails, ASP.NET MVC , & Sinatra.
We can say that the development in Laravel must be an delightful, innovative, satisfying.
Q2. What is Laravel auth?
Laravel auth (auth means authentication) is the process of recognizing the user credentials.Most websites will need a way to allow users to log in so that they can access resources , update information & so on.
Laravel makes implementing authentication very simple . The authentication fileis located at the config/auth.php , which carry some well docmented options for improving the behaviour of the authentication services.
By deafault , Laravel includes an App\User model in your app directory. This model may be used with the default driver. Eloquent is the default driver & you may also use the database authentication driver .
Q3. How to use laravel or condition?
Eloquent is the default driver in laravel , Eloquent is a great thing – you can build your step-by-step & then call get() method. However sometimes it is difficult for complex queries.
Lets take a example :
we need to filter male customers age 20+ or female customers aged 60+. Simple Eloquent query will be:
// . . . $q->where(‘gender’, ‘male’); $q->orWhere(‘age’, ‘>=’ , 20); $q->where(‘gender’, ‘female’); $q->orWhere(‘age’, ‘>=’ , 60);
Now look at the MYSQL query for this codition , it wouldn’t have any brackets :
...WHERE gender = ‘male’ and age >= 20 or gender = ‘female’ and age >= 60
Q4. What are Laravel Helpers?
Laravel include a range of Helpers (PHP function) that you can call anywhere within your application. They make your venture suitable for working .
You can also define helper by your own to avoid repeating in the same code. It ensures better maintainability of your application. It is convenient for doing things like working with arrays,file paths, strings, & routes , among other things like the dd() function.
Helper are grouped together based on the performance. List of Helper group is given below :
Q5. What are laravel traits?
Trait is the mechanism for code reuse in single inheritance language i.e. PHP . Simply we can say that the a class can only inherit from one other class.
Trait , like an abstarct class, cannot be detect on it’s own . It’s great that we can write some code, reuse that again & again throughout our codebase more efficiently.
Creating a trait is very easy, there is not much code is required to create a trait. We will name the folder to store all my traits is Traits , using namespace App\Traits .
Now here we will show you the structure of trait , it has function called verifyAndStoreImage .
<?php namespace App\Traits; trait StoreImageTrait { public function verifyAndStoreImage() { } }
Q6. Where laravel logs are stored?
The Laravel logging facilities provide a simple layer on the top of the powerful Monolog library. By default , Laravel is configured to create a single log file.
File is stored in app/storage/logs/laravel.log
if you want to write the information in the log , so you can write as follows :
Log::info(‘information’); Log::warning(‘warning’) Log::error(‘error’)
Here are few most common log levels :-
Q7. What are Laravel Guards?
A Guard is way of supplying the logic that is used to identify authenticated users . Laravel provides different guards like sessions and tokens. The session guard maintains the state of the user in each request by the cookies , and on the other hand , token guard authenticates the user by checking a valid token in every request.
Guard instruct laravel to store and retrieve the information about the users. You can define custom using the extend method on the facades . You have to place the call to extend in the service provider i.e.AuthServiceProvider.
<?php namespace App\Providers; use App\Services\Auth\JwtGuard; use Illuminate\Support\Facades\Auth; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * Register any application authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Auth::extend('jwt', function ($app, $name, array $config) { // Return an instance of Illuminate\Contracts\Auth\Guard... return new JwtGuard(Auth::createUserProvider($config['provider'])); }); } }
Q8. How to clear cache in Laravel?
We can clear cache in Laravel by the command line (CLI). In Larva projects we need to make cache for superior completion. However sometimes our application is development mode then we want to do is not to cured due to cache. This time we are facing a problem , so we have to clear the cache.
php artisan route:cache
php artisan cache:clear
php artisan view:clear
php artisan optimize
Route::get(‘/clear-cache’, function() { $exitCode = Artisan::call(‘cache:clear’); return “Cache is cleared”; });
Q9. What is Eloquent in Laravel?
Eloquent OMR(Object-relational Mapping) included with Laravel provides an attractive , simple Active record implementation for the working with database. Eloquent is object that is representative of your database and tables , in other words it’s act as controller between user and DBMS.
For eg, DB raw query, select * from post LIMIT 1 Eloquent equivalent, $post = Post::first(); $post->column_name;
It’s way of representing your database values with objects you can easily use with your application.
Eloquent relationships are defined as methods on your Eloquent model classes :-
-> One To One - hasOne -> One To Many - hasMany -> One To Many(Inverse) - belongsTo -> Many To Many - belongsToMany -> Has Many Through – hasManyThrough -> Polymorphic Relations -> Many To Many Polymorphic Relation
Q10. What is mass assignment and fillable in Laravel?
Mass assignment is a process of sending an array of data that will be saved to the specified model at once . In general, you don’t need to save the data on your model on one basis , but rather in a single process.
Mass assignment is good, but there are certain security problems behind it. What if someone passes a value to the model and without protection they can definitely modify all fields including the ID. That’s not good.
Fillable is the property of model, this property specifies which attributes in the table should be mass-assignable.
protected $fillable = [‘first_name’ , ‘last _name’, ‘email’]; for example let’s say you have a user model with :- protected $hidden = array(‘password’); protected $fillable = [‘username’ , ‘email’]; and for your registration logic you have something like : $user = new User( [ ‘username’ => Input::get(‘username’) , ‘email’ => Input::get(‘email’), ] ) ; $user ->password = Hash::make(Input::get(‘password’));
Q11. Enlist few popular packages of Laravel?
Laravel packages are used for developing web applications , it offers easy & quick development . Few popular packages of laravel are :-
Q12. What is a facade in Laravel?
A facade is a class wrapping a complex library to provide a simple and more readable interface to it. Facade pattern is a softwarre design pattern that is oftn used in object oriented programming language .
The following are the steps to create facade in laravel :-
Step 1 :- Create PHP Class File.
Step 2:- Bind that class to Service Provider.
Step 3 :- Register that ServiceProvider to Config\app.php as providers
Config\app.php as providers
Step 4 :- Create Class which is this class extends to
lluminate\Support\Facades\Facade.
Step 5 :- Register point 4 to Config\app.php as aliases.
Q13. How to enable Laravel maintenance mode?
There are two ways to enable & disable maintenance mode in laravel 5. When your applications in maintenance mode , a custom view will be displayed for all requests into your application . This makes it easy to “disable” your application while it is updating or when you are performing maintenance . A maintenance mode check is included in the default middleware stack of your application is in maintenance mode , a MaintenanceModeException will be thrown with a status code of 503 .
Q14. How to use laravel multiple where?
We have a simple way to use laravel multiple where by adding an array of condition where function of laravel Eloquent to create multiple where clauses . It works , but it’s not elegant .
Example :-
$results = User::where('this', '=', 1) ->where('that', '=', 1) ->where('this_too', '=', 1) ->where('that_too', '=', 1) ->where('this_as_well', '=', 1) ->where('that_as_well', '=', 1) ->where('this_one_too', '=', 1) ->where('that_one_too', '=', 1) ->where('this_one_as_well', '=', 1) ->where('that_one_as_well', '=', 1) ->get();
Here look at some other examples :-
$result=DB::table(‘users’)->where(array( ‘column1’ => value1, ‘column2’ => value2, ‘column3’ => value3)) ->get();
Another way to creating scope :-
public function scopeActive($query) { return $query->where('active', '=', 1); } public function scopeThat($query) { return $query->where('that', '=', 1); }
Then call the scope given below :
$users = User::active()->that()->get();
Q15. List types of relationships Laravel Supports?
Database tables are often related to one another .There are basically diffrent types of relationships are :-
Q16. What is Laravel nullable?
A field that is allowed to have no values is called nullable. It may be null variable , object , type , null column .
If someone wants to set the column in the table as null and he/she is doing on rollback up & on down function it will not work .
In the latest version of laravel 5 you will write it as :-
$table->...->nullable(false)->change();
Q17. How to set session in Laravel?
Session in Laravel provides a wide range of inbuilt methods for setting the session data. In laravel , session is a parameter passing mechanism which help us to store the data across multiple requests.
In laravel there are some built in session drivers , some of them are given below :- File , cookie , database , apc , memcached , redis , array .
Setting a single variable in sesion :-
Syntax :- Session::put(‘key’ , ‘value’); Example:- Session::put(‘email’ , $data[‘email’]); Session::put(‘email’ , $email); Session::put(‘email’ , ‘utkarshpaliwal111@gmail.com’);
Q18. Enlist few builtin string helpers in Laravel?
Laravel provides some pretty cool helper functions to make common tasks easier. Some of builtin string helpers in Laravel are given below :-
Q19. What are laravel named routes?
It is an important feature in the Laravel framework. It allows you to refer to the routes when generating URLs or redirects to the specific routes. In short, we can say that the naming route is the way of providing a nickname to the route.
Most of the routes for your application will be defined in the app/routes.php file. The simplest Laravel routes consist of a URI and a Closure callback.
Syntax of defining naming routes:-
We can define the named routes by chaining the name method onto the route definition:-
Basic GET Route :-
Route::get(‘/’,function() { return ‘Hello world’; });
Q20. What are collections in Laravel?
Laravel collections are very supreme distributor of the Laravel framework. They are what PHP arrays should be, but better.
The collection class implements some interfaces given below :-
Creating a new collection :-
we can create a new colection by observing the Illuminate\Support\Collection class.
Here is an easy example using the collect() helper method:
$newCollection = collect([1,2,3,4,5,6,7,8,9,10]);
some of available methods on the collection class are:-
"Very good information. Good job. vebcodex.com
"It's really thanks ful :)
Valid name is required.
Valid name is required.
Valid email id is required.
Sharad Jaiswal
Sharad Jaiswal is Sr. Web Developer from Noida area. He have rich experience in PHP, Angular Js, React, javascript and Node .If you any query or project on these programming you can drop your enquiry in comment section.