Posts

Showing posts from October, 2021

How to pass CSRF token with ajax request?

In between head, tag put and in Ajax, we have to add $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });

How to get data between two dates in Laravel?

In Laravel, we can use whereBetween() function to get data between two dates. Example Users::whereBetween('created_at', [$firstDate, $secondDate])->get();

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', ]; }

How do you make and use Middleware in Laravel?

It acts as a middleman between a request and a response. Middleware is a type of filtering mechanism used in Laravel application. We can create middelware with php artisan make:middleware UsersMiddleware Here "UsersMiddleware" is the name of Middleware. After this command a "UsersMiddleware.php" file created in app/Http/Middleware directory. After that we have to register that middleware in kernel.php (available in app/Http directory) file in "$routeMiddleware" variable. 'Users' => \App\Http\Middleware\UsersMiddleware::class, Now we can call "Users" middleware where we need it like controller or route file. We can use it in controller file like this. public function __construct() { $this->middleware('Users'); } In route file we can use like this. Route::group(['middleware' => 'Users'], function () { Route::get('/', 'HomeController@index'); });

How to use Stored Procedure in Laravel?

How to create a Stored Procedure To create a Stored Procedure you can execute given code in your MySQL query builder directly or use phpmyadmin for this. DROP PROCEDURE IF EXISTS `get_subcategory_by_catid`; delimiter ;; CREATE PROCEDURE `get_subcategory_by_catid` (IN idx int) BEGIN SELECT id, parent_id, title, slug, created_at FROM category WHERE parent_id = idx AND status = 1 ORDER BY title; END ;; delimiter ; After this, you can use this created procedure in your code in Laravel. How to use stored procedure in Laravel $getSubCategories = DB::select( 'CALL get_subcategory_by_catid('.$item->category_id.')' );

How to upload files in laravel?

We have to call Facades in our controller file with this : use Illuminate\Support\Facades\Storage; Example if($request->hasFile(file_name')) { $file = Storage::putFile('YOUR FOLDER PATH', $request->file('file_name')); }

How to use multiple databases in Laravel?

To use multiple databases in Laravel, follow these steps carefully. Ensure these settings in the .env file Add these following lines of code in the config/database.php file to clearly define the relationship between the two databases Execute the query with particular database. 1. Ensure these settings in the .env file DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=your_db_name DB_USERNAME=bestinterviewquestion DB_PASSWORD=admin@123 DB_CONNECTION_SECOND=mysql DB_HOST_SECOND=localhost DB_PORT_SECOND=3306 DB_DATABASE_SECOND=your_db_name2 DB_USERNAME_SECOND=bestinterviewquestion DB_PASSWORD_SECOND=admin@12345 2. Add these following lines of code in the config/database.php file to clearly define the relationship between the two databases 'mysql' => [ 'driver' => env('DB_CONNECTION'), 'host' => env('DB_HOST'), 'port' => env('DB_PORT'), 'database' => env('DB_DATAB...

How do you call Middleware in laravel?

In laravel, we can call multiple Middlewares in Controller file and route file. 1. In Controller file, you can call like this. public function __construct() { $this->middleware(['revalidateBackHistory', 'validateUser']); } 2. In route file, you can call multiple middleware like this. Route::get('/', function () { // })->middleware(['firstMiddle', 'secondMiddle']);

How to clear cache in Laravel?

Please run below artisan commands step wise step. php artisan config:clear php artisan cache:clear composer dump-autoload php artisan view:clear php artisan route:clear

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([Conditions],[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?

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?

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?

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 redirect form controller to view file in laravel?

We can use return redirect('/')->withErrors('You can type your message here'); return redirect('/')->with('variableName', 'You can type your message here'); return redirect('/')->route('PutRouteNameHere');

How to use Ajax in any form submission?

Example

How to get current route name?

request()->route()->getName()

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 }}

How to create custom validation rules with Laravel?

Run this php artisan make:rule OlympicYear After that command it generates a file app/Rules/OlympicYear.php We can write rule in the passes() in OlympicYear.php generated file. It will return true or false depending on condition, which is this in our case public function passes($attribute, $value) { return $value >= 1896 && $value validate($request, ['year' => new OlympicYear]); }

How to use Where null and Where not null eloquent query in Laravel?

Where Null Query DB::table('users')->whereNull('name')->get(); Where Not Null Query DB::table('users')->whereNotNull('name')->get();

How to add multiple AND conditions in laravel query?

We can add multiple AND operator at in a single where() conditions as well as we can also add separate where() for particular AND condition. Example DB::table('client')->where('status', '=', 1)->where('name', '=', 'bestinterviewquestion.com')->get(); DB::table('client')->where(['status' => 1, 'name' => 'bestinterviewquestion.com'])->get();

What is fillable in laravel model?

It is an array which contains all those fields of table which can be create directly new record in your Database table. Example class User extends Model { protected $fillable = ['username', 'password', 'phone']; }

How to get user details when he is logged in by Auth?

Example use Illuminate\Support\Facades\Auth; $userinfo = Auth::user(); print_r($userinfo );

How to check Ajax request in Laravel?

You can use the following syntax to check ajax request in laravel. if ($request->ajax()) { // Now you can write your code here. }

How to check if value is sent in request?

To check the email value is sent or not in request, you can use $request->has('email') Example if($request->has('email')) { // email value is sent from request } else { // email value not sent from request }

What are string and array helpers functions in laravel?

Laravel includes a number of global "helper" string and array functions. These are given below:- Laravel Array Helper functions Arr::add() Arr::has() Arr::last() Arr::only() Arr::pluck() Arr::prepend() etc Laravel String Helper functions Str::after() Str::before() Str::camel() Str::contains() Str::endsWith() Str::containsAll() etc

What is Database Migration and how to use this in Laravel?

Database migration is like the version control of the database, which allows the team to modify and share the database schema of the application. Database migrations are paired with the schema builder of Laravel which is used to build the database schema of the application. 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. Example You can generate a migration & its file with the help of make:migration. Syntax : php artisan make:migration blog A current_date_blog.php file will be create in database/migrations

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.

How to enable query log in laravel?

Our first step should be DB::connection()->enableQueryLog(); After our query, it should be placed $querieslog = DB::getQueryLog(); After that, it should be placed dd($querieslog) Example DB::connection()->enableQueryLog(); $result = User:where(['status' => 1])->get(); $log = DB::getQueryLog(); dd($log);

How to make a constant and use globally?

You can create a constants.php page in config folder if does not exist. Now you can put constant variable with value here and can use with Config::get('constants.VaribleName'); Example return [ 'ADMINEMAIL' => 'info@bestinterviewquestion.com', ]; Now we can display with Config::get('constants.ADMINEMAIL');

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 value of the variable. By default it is 'lifetime' => 120. According to your requirement update this variable. Example 'lifetime' => 180