Laravel Tutorials
- What is laravel
- Laravel Installation
- Directory Structure
- htaccess
- Remove public from url
- Artisan Command
- Laravel Configuration
- Routing Configuration
- Namespaces
- Request
- Response
- Controller
- Model
- User Authentication
- Multi User Authentication
- Database Seeding
- Database
- Database Query
- ORM
- One-to-One Relationship
- One-to-Many Relationship
- Many to Many Eloquent Relationship
- Has One Through
- Has Many Through
- Querying Relations
- Middleware
- Laravel Views
- Blade Views
- Print data on view page
- Get Site URL
- Get URL Segment
- Get images from Storage folder
- Clear cache
- Form Class not found
- Flash Message in laravel
- Redirections
- path
- CRUD Projerct
- CRUD in Laravel
- CRUD progran
- Laravel Validation
- Jquery Validation
- Cookie
- Session
- Email Send in laravel
- File uploading
- CSRF Protection
- Helper in Laravel
- Helper Functions
- Guzzle Http Client
- Paypal Payment Gatway Integration
- Cron Job in laravel
- Flash message
- path
- Errors Handling
- Date Format
- Date Format Validation
- Display Image on View Page
- Update User Status using toggle button
- Delete Multiple Records using Checkbox in Laravel?
- Confirmation Before Delete Record
- Delete image from storage
- Remove/Trim Empty & Whitespace From Input Requests
- Block IP Addresses from Accessing Website
- How to Disable New User Registration in Laravel
- Redirect HTTP To HTTPS Using Laravel Middleware
- CKEditor
- slug generate unique
- Prevent Browser's Back Button After Logout
- Datatable dunamically
- encrypt & Decript
- Download File
- Rest API
- Shopping Cart
- Shopping Cart Example
- Dynamic Category-Subcategory Menu
- Ajax Search
- Interview Question
- laravel Tutorilal link
- laravel Tutorilal
Important Links
Laravel Interview Questions?
What is Laravel?
What is Laravel?+
Laravel is a free and open-source PHP framework based on MVC design pattern.
What is the latest version of Laravel?
What is the latest version of Laravel? +
7.0, released on 3rd March 2020.
When was Laravel first released?
When was Laravel first released? +
The first version of laravel is released on 9 June 2011.
Laravel is Created By
Laravel is Created By +
Taylor Otwell
How to extend login expire time in Auth?
How to extend login expire time in Auth? +
You can extend the login expire time with config\session.php this file location. Just update lifetime the variables value. By default it is 'lifetime' => 120.
the server requirements for Laravel 7?
the server requirements for Laravel 7? +
PHP version >= 7.2.0
What is middleware in Laravel?
What is middleware in Laravel? +
In Laravel, middleware operates as a bridge and filtering mechanism between a request and response. It verifies the authentication of the application users and redirects them according to the authentication results. We can create a middleware in Laravel by executing the following command.
Example: If a user is not authenticated and it is trying to access the dashboard then, the middleware will redirect that user to the login page.
// Syntax
php artisan make:middleware MiddelwareName
// Example
php artisan make:middleware UserMiddelware
Now UserMiddelware.php file will create in app/Http/Middleware
What is Database Migration and how to use this in Laravel?
What is Database Migration and how to use this in Laravel? +
It is a type of version control for our database. It is allowing us to modify and share the application's database schema easily.
A migration file contains two methods up() and down().
up() is used to add new tables, columns, or indexes database and the down() is used to reverse the operations performed by the up method.
Syntax : php artisan make:migration blog
What is reverse Routing in Laravel?
What is reverse Routing in Laravel? +
Reverse routing is generated URL’s based totally on route. It makes our application so a lot greater flexible.
Example
Route:: get(‘login’, ‘login@index’); // It is normal route but after reverse routing, we can also call this link with
{{ HTML::link_to_action('login@index') }}
How to pass CSRF token with ajax request?
How to pass CSRF token with ajax request? +
In between head, tag put <meta name="csrf-token" content="{{ csrf_token() }}"> and in Ajax, we have to add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
What is service providers?
What is service providers? +
In Laravel, service providers are the center of overall Laravel application bootstrapping. User applications, as well as core services of Laravel, are bootstrapped with service providers. These powerful tools are used by developers to manage class dependencies and perform dependency injection. To create a service provider, we have to use the below-mentioned artisan command.
You can use php artisan make: provider ClientsServiceProvider artisan command to generate a service provider :
How to variable is empty or not in Laravel?
+
@empty($mahi)
// $mahi is "empty"...
@endisset
How to get data between two dates in Laravel?
How to get data between two dates in Laravel? +
In Laravel, we can use whereBetween() function to get data between two dates.
Example
Blog::whereBetween('created_at', [$dateOne, $dateTwo])->get();
How to turn off CSRF protection for a particular route in Laravel?
How to turn off CSRF protection for a particular route in Laravel? +
We can add that particular URL or Route in $except variable. It is present in the app\Http\Middleware\VerifyCsrfToken.php file.
Example
class VerifyCsrfToken extends BaseVerifier {
protected $except = [
'Pass here your URL',
];
}
What is Facade and how it can be used in Laravel?
What is Facade and how it can be used in Laravel? +
Facades offer a static interface to classes available inside the application's service container. They serve as static proxies for underlying classes present in the service container.
All the facades are defined in the namespace Illuminate\Support\Facades for easy accessibility and usability.
Example
use Illuminate\Support\Facades\Cache;
Route::get('/cache', function () {
return Cache::get('PutkeyNameHere');
});
What is the use of dd() in Laravel?
What is the use of dd() in Laravel? +
It is a helper function which is used to dump a variable's contents to the browser and stop the further script execution. It stands for Dump and Die.
Example
dd($array);
How to make a helper file in laravel?
How to make a helper file in laravel? +
We can create a helper file using Composer. Steps are given below:-
Please create a "app/helpers.php" file that is in app folder.
Add
"files": [
"app/helpers.php"
]
in "autoload" variable.
Now update your composer.json with composer dump-autoload or composer update
What are the steps to install Laravel with composer?
What are the steps to install Laravel with composer? +
Download composer from https://getcomposer.org/download (if you don’t have a composer on your system)
Open cmd
Goto your htdocs folder.
C:\xampp\htdocs>composer create-project laravel/laravel projectname
OR
If you install some particular version, then you can use
composer create-project laravel/laravel project name "5.6"
If you did not mention any particular version, then it will install with the latest version.
What is PHP artisan in laravel? Name some common artisan commands?
What is PHP artisan in laravel? Name some common artisan commands? +
Laravel supports various artisan commands like
php artisan list;
php artisan –version
php artisan down;
php artisan help;
php artisan up;
php artisan make:controller;
php artisan make:mail;
php artisan make:model;
php artisan make:migration;
php artisan make:middleware;
php artisan make:auth;
php artisan make:provider etc.;
+
What is the difference between {{ $username }} and {!! $username !!} in Laravel?
What is the difference between {{ $username }} and {!! $username !!} in Laravel? +
{{ $username }} is simply used to display text contents but {!! $username !!} is used to display content with HTML tags if exists.
What is laravel Service container?
What is laravel Service container? +
Service Container is a powerful tool which is used to manage class dependencies and perform dependency injection. It is also known as the IoC container. It offers several benefits to users such as.
Advantages of Service Container
Freedom to manage class dependencies on object creation.
Service contain as Registry.
Ability to bind interfaces to concrete classes.
How to use session in laravel?
How to use session in laravel? +
Retrieving Data from session
session()->get('key');
2. Retrieving All session data
session()->all();
3. Remove data from session
session()->forget('key'); or session()->flush();
4. Storing Data in session
session()->put('key', 'value');
How to get last inserted id using laravel query?
How to get last inserted id using laravel query? +
In case you are using save()
$blog = new Blog;
$blog->title = ‘Best Interview Questions’;
$blog->save()
// Now you can use (after save() function we can use like this)
$blog->id // It will display last inserted id
In case you are using insertGetId()
$insertGetId = DB::table(‘blogs’)->insertGetId([‘title’ => ‘Best Interview Questions’]);
How to use cookies in laravel?
How to use cookies in laravel? +
1. How to set Cookie
To set cookie value, we have to use Cookie::put('key', 'value');
2. How to get Cookie
To get cookie Value we have to use Cookie::get('key');
3. How to delete or remove Cookie
To remove cookie Value we have to use Cookie::forget('key')
4. How to check Cookie
To Check cookie is exists or not, we have to use Cache::has('key')
What is Auth? How is it used?
What is Auth? How is it used? +
Laravel Auth is the process of identifying the user credentials with the database. Laravel managed it's with the help of sessions which take input parameters like username and password, for user identification. If the settings match then the user is said to be authenticated.
Auth is in-built functionality provided by Laravel; we have to configure.
We can add this functionality with php artisan make: auth
Auth is used to identifying the user credentials with the database.
What is with() in Laravel?
What is with() in Laravel? +
with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.
How to remove /public from URL in laravel?
How to remove /public from URL in laravel? +
Copy .htaccess file from public folder and now paste it into your root.
Now rename server.php file/page to index.php on your root folder.
Now you can remove /public word from URL and refresh the page. Now it will work.
How to get user’s ip address in laravel?
How to get user’s ip address in laravel? +
You can use request()->ip()
You can also use : Request::ip() but in this case we have to call namespace like this : Use Illuminate\Http\Request;
What are the difference between softDelete() & delete() in Laravel?
What are the difference between softDelete() & delete() in Laravel? +
1. delete()
In case when we used to delete in Laravel then it removed records from the database table.
Example:
$delete = Post::where(‘id’, ‘=’, 1)->delete();
2. softDeletes()
To delete records permanently is not a good thing that’s why laravel used features are called SoftDelete. In this case, records did not remove from the table only delele_at value updated with current date and time.
Firstly we have to add a given code in our required model file.
use SoftDeletes;
protected $dates = ['deleted_at'];
After this, we can use both cases.
$softDelete = Post::where(‘id’, ‘=’, 1)->delete();
OR
$softDelete = Post::where(‘id’, ‘=’, 1)->softDeletes();
What is Eloquent ORM in Laravel?
What is Eloquent ORM in Laravel? +
The Eloquent ORM present in Laravel offers a simple yet beautiful ActiveRecord implementation to work with the database. Here, each database table offers a corresponding model which is used to interact with the same table. We can create Eloquent models using the make:model command.
It has many types of relationships.
One To One relationships
One To Many relationships
Many To Many relationships
Has Many Through relationships
Polymorphic relationships
Many To Many Polymorphic relationships
What is composer lock in laravel?
What is composer lock in laravel? +
After running the composer install in the project directory, the composer will generate the composer.lock file.It will keep a record of all the dependencies and sub-dependencies which is being installed by the composer.json.
Which template engine laravel use?
Which template engine laravel use? +
Laravel uses "Blade Template Engine". It is a straightforward and powerful templating engine that is provided with Laravel.
How to create real time sitemap.xml file in Laravel?
How to create real time sitemap.xml file in Laravel? +
We can create all web pages of our sites to tell Google and other search engines like Bing, Yahoo etc about the organization of our site content. These search engine web crawlers read this file to more intelligently crawl our sites.
How to use skip() and take() in Laravel Query?
How to use skip() and take() in Laravel Query? +
We can use skip() and take() both methods to limit the number of results in the query. skip() is used to skip the number of results and take() is used to get the number of result from the query.
Example
$posts = DB::table('blog')->skip(5)->take(10)->get();
// skip first 5 records
// get 10 records after 5
What is faker in Laravel?
What is faker in Laravel? +
Faker is a type of module or packages which are used to create fake data for testing purposes. It can be used to produce all sorts of data.
It is used to generate the given data types.
Lorem text
Numbers
Person i.e. titles, names, gender, etc.
Addresses
DateTime
Phone numbers
Internet i.e. domains, URLs, emails etc.
Payments
Colour, Files, Images
UUID, Barcodes, etc
In Laravel, Faker is used basically for testing purposes.
How to clear complete cache in Laravel?
How to clear complete cache in Laravel? +
artisan commands step wise step.
php artisan config:clear
php artisan cache:clear
composer dump-autoload
php artisan view:clear
php artisan route:clear
What is seed in laravel?
What is seed in laravel? +
Laravel offers a tool to include dummy data to the database automatically. This process is called seeding. Developers can add simply testing data to their database table using the database seeder. It is extremely useful as testing with various data types allows developers to detect bugs and optimize performance. We have to run the artisan command make:seeder to generate a seeder, which will be placed in the directory database/seeds as like all others.
How to create database seeder
To generate a seeder, run the make:seeder Artisan command. All seeders generated by the laravel will be placed in the database/seeds directory:
php artisan make:seeder AdminTableSeeder
How to use update query in Laravel?
How to use update query in Laravel? +
With the help of update() function, we can update our data in the database according to the condition.
Example
Blog::where(['id' => $id])->update([
'title' => ’Best Interview Questions’,
‘content’ => ’Best Interview Questions’
]);
OR
DB::table("blogs")->where(['id' => $id])->update([
'title' => ’Best Interview Questions’,
‘content’ => ’Best Interview Questions’
]);
How to use multiple OR condition in Laravel Query?
How to use multiple OR condition in Laravel Query? +
Blog::where(['id' => 5])->orWhere([‘username’ => ‘info@bestinterviewquestion.com’])->update([
'title' => ‘Best Interview Questions’,
]);
Please write some additional where Clauses in Laravel?
Please write some additional where Clauses in Laravel? +
Laravel provides various methods that we can use in queries to get records with our conditions.
These methods are given below
where()
orWhere()
whereBetween()
orWhereBetween()
whereNotBetween()
orWhereNotBetween()
wherein()
whereNotIn()
orWhereIn()
orWhereNotIn()
whereNull()
whereNotNull()
orWhereNull()
orWhereNotNull()
whereDate()
whereMonth()
whereDay()
whereYear()
whereTime()
whereColumn()
orWhereColumn()
whereExists()
How to use updateOrInsert() method in Laravel Query?
How to use updateOrInsert() method in Laravel Query? +
updateOrInsert() method is used to update an existing record in the database if matching the condition or create if no matching record exists.
Its return type is Boolean.
Syntax
DB::table(‘blogs’)->updateOrInsert([Conditons],[fields with value]);
Example
DB::table(‘blogs’)->updateOrInsert(
['email' => 'info@bestinterviewquestion.com', 'title' => 'Best Interview Questions'],
['content' => 'Test Content']
);
How to check table is exists or not in our database using Laravel?
How to check table is exists or not in our database using Laravel? +
We can use hasTable() to check table exists in our database or not.
Syntax
Schema::hasTable('users'); // here users is the table name.
Example
if(Schema::hasTable('users')) {
// table is exists
} else {
// table is not exists
}
How to check column is exists or not in a table using Laravel?
How to check column is exists or not in a table using Laravel? +
if(Schema::hasColumn('admin', 'username')) ; //check whether admin table has username column
{
// write your logic here
}
What are the difference between insert() and insertGetId() in laravel?
What are the difference between insert() and insertGetId() in laravel? +
Inserts(): This method is used for insert records into the database table. No need the “id” should be autoincremented or not in the table.
Example
DB::table('bestinterviewquestion_users')->insert(
['title' => 'Best Interview Questions', 'email' => ‘info@bestinterviewquestion.com’]
);
It will return true or false.
insertGetId(): This method is also used for insert records into the database table. This method is used in the case when an id field of the table is auto incrementing.
It returns the id of current inserted records.
Example
$id = DB::table('bestinterviewquestion_users')->insert(
['title' => 'Best Interview Questions', 'email' => ‘info@bestinterviewquestion.com’]
);
How to change your default database type in Laravel?
How to change your default database type in Laravel? +
Please update 'default' => env('DB_CONNECTION', 'mysql'), in config/database.php. Update MySQL as a database whatever you want.
What is eager loading in Laravel?
What is eager loading in Laravel? +
Eager loading is used when we have to fetch some useful data along with the data which we want from the database. We can eager load in laravel using the load() and with() commands.
How to upgrade form laravel 5 to laravel 6?
How to upgrade form laravel 5 to laravel 6? +
Open the laravel project inside the code editor.
Go to the Composer.json file and change the laravel/framework from 5 to 6.
Open the terminal and write the command – composer update and hit enter to wait for the update to complete.
After finished run the server command (PHP artisan serve) and run the project in a browser.
After this , again go to terminal and write command –(composer require laravel/ui) and hit enter and download the packages.
Then, for creating the auth file write the command ( PHP artisan ui vue-auth) to make the auth file in laravel 6.0.
In this way, we can upgrade from laravel 5 to laravel 6.
How to generate application key in laravel?
How to generate application key in laravel? +
You can use php artisan key:generate to generate your application key.
How to pass multiple variables by controller to blade file?
How to pass multiple variables by controller to blade file? +
$valiable1 = 'Best';
$valiable2 = 'Interview';
$valiable3 = 'Question';
return view('frontend.index', compact('valiable1', valiable2', valiable3'));
In you View File use can display by {{ $valiable1 }} or {{ $valiable2 }} or {{ $valiable3 }}
validations in laravel
validations in laravel +
By default Laravel’s base controller class uses a ValidatesRequeststrait 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.
What is the service container in laravel?
What is the service container in laravel? +
Service Container is a powerful tool that is used to manage class dependencies and perform dependency injection. It is also known as the IoC container. It offers several benefits to users such as.
Advantages of Service Container
Freedom to manage class dependencies on object creation.
Service contain as Registry.
Ability to bind interfaces to concrete classes.
How to Access Config Value in Laravel?
How to Access Config Value in Laravel? +
use confige() method in controller
public function index()
{
$config1 = config('database.default');
$config2 =Config::get('app.name');
dd($config1);
dd($config2);
}
How To Get .env Variable In Laravel?
How To Get .env Variable In Laravel? +
you can get env file variable by using env() helper.
public function index()
{
$value = env("DB_DATABASE");
dd($value);
}
How To Get Current Page Url in Jquery ?
How To Get Current Page Url in Jquery ? +
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Get Current Page URL</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
var currentURL = window.location.href;
alert(currentURL);
############### OR #################
var currentURL = $(location).attr("href");
alert(currentURL);
############### OR #################
var currentURL = window.location;
alert(currentURL);
############### OR #################
var currentURL=location.protocol + '//' + location.host + location.pathname;
alert(currentURL);
});
});
</script>
</head>
<body>
<button type="button">Get URL</button>
</body>
</html>
How to Check Array Empty in laravel Blade?
How to Check Array Empty in laravel Blade? +
<div class="card-body">
@forelse ($products as $product)
<p class="bg-danger text-white p-1">product</p>
@empty
<p class="bg-danger text-white p-1">No product</p>
@endforelse
</div>
How to Check Array Empty in laravel Blade?
How to Check Array Empty in laravel Blade? +
<div class="card-body">
@empty($products)
<p class="bg-danger text-white p-1">product</p>
@else
<p class="bg-danger text-white p-1">no product</p>
@endempty
</div>
How to Check Array Empty in laravel Blade?
How to Check Array Empty in laravel Blade? +
<div class="card-body">
@if(empty($products))
<p class="bg-danger text-white p-1">product</p>
@else
<p class="bg-danger text-white p-1">No product</p>
@endif
</div>
How to Check Array Empty in laravel Blade?
How to Check Array Empty in laravel Blade? +
<div class="card-body">
@if(count($products) > 0)
<p class="bg-danger text-white p-1">product</p>
@else
<p class="bg-danger text-white p-1">No product</p>
@endif
</div>
How to Write PHP Code in Laravel Blade
How to Write PHP Code in Laravel Blade +
@php
$myArray = [
"name" => "abc",
"city" => "def",
"mobile" => 123
];
print_r($myArray);
@endphp
<?php
$myArray = [
"name" => "abc",
"city" => "def",
"mobile" => 123
];
print_r($myArray);
?>
isset condition in laravel blade
isset condition in laravel blade +
@isset($myVariable)
// $myVariable is defined and is not null...
@endisset
How to check File exist in Folder or Not in Laravel ?
How to check File exist in Folder or Not in Laravel ? +
public function index()
{
if (File::exists(public_path('img/dummy.jpg'))) {
dd('File is Exists');
}else{
dd('File is Not Exists');
}
}
public function index()
{
if (Storage::exists(public_path('img/dummy.jpg'))) {
dd('File is Exists');
}else{
dd('File is Not Exists');
}
}
public function index()
{
if (file_exists(public_path('img/dummy.jpg'))) {
dd('File is Exists ');
}else{
dd('File is Not Exists');
}
}
stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
stream_socket_enable_crypto(): SSL operation failed with code 1.
OpenSSL Error messages: error:14090086:SSL
routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed +
There are two ways to solve this issue.
1. Change the protocol in app/config/email.php
--> smtp to mail
2. Add the below code, where you disable SSL which is fine in a testing environment and not in a production environment. (Working in laravel 5.1,5.2,5.4,5.5,5.7,5.8)
'stream' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
],
Database connection not configured
Database connection [db_name] not configured. +
php artisan config:cache
MySQL Not Starting
MySQL Not Starting +
If your mysql not starting on xampp server then follow these steps
Step 1: Go to your C:\xampp\mysql\backup directory
Step 2: Copy all files
Step 3: Now go to your C:\xampp\mysql\data directory
Step 4: Past all files.
Step 5: Now stop your xampp and start again. After that I hope your mysql will start perfectly.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
File name : index.php
File name : index.php
File name : index.php
File name : index.php
File name : index.php