Wednesday, 20 October 2021

Set Base URL for Assets in Laravel Applications

Setting the Base URL for Assets in your Laravel Applications is very important to make sure all assets like stylesheets, images, and all javascript are properly loading and running without any issues.

Properly set or configured base URLs make sure that our application is accessible in different
types of environments like staging, and production.

1. asset() Helper Function

asset() helper function is very useful when it comes to loading assets of the application.

by default, this helps use the APP_URL value that is defined in the .env file.


2. APP_URL in the .env File

variable app_url in the configuration file decides the base URL of your application.

 APP_URL=http://shoplocal.test

For production update it to the live URL

 APP_URL=http://myabcshop.com


3. Steps to Set Base URL for Assets in Laravel Applications:

1. Using Content Delivery Network (CDN) for Hosting Assets

a) If you are planning to use CDN URLs for your Laravel application then. Open the environment configuration file .env in the root of your Laravel application. It looks something like the below screenshot.


b) Also add the CDN asset URL in AppServiceProvider to register this custom asset URL:

use Illuminate\Support\Facades\URL;
public function boot()
{
   if (env('ASSET_URL')) 
  {
     URL::forceRootUrl(env('ASSET_URL'));
   }
}

Now after updating everything, it will generate CDN URLs for the application

Additionally, if we add or update the public value in asset_url like 

Add ASSET_URL=public 

it will set the asset folder path to the public folder


c) Clear the configuration cache 

To clear the configuration cache to get the updated setting from the configuration we need to run the
command

php artisan config:cache 

This will clear the cache of the configuration.

Friday, 20 August 2021

How to Debug SQL Queries in Laravel

Debugging SQL queries in complex Laravel projects can be challenging sometimes. We can debug database queries in Laravel by following different methods and techniques.

1. Dump and Die dd() function

dd() function will stop execution and display information. It is used to display the SQL query results.


For example:$p = DB::table('products_data')->get();
dd($p);

or

Product::all()->dd();


The above queries will dump and die the SQL query results.

2. dump() function

dump function displays debug information and continues execution.

For example:

Category::all()->dump();

3. toSql() method 

We can use toSql() method in any eloquent query in Laravel with the help of this method
we can get SQL raw query very easily without executing it.


For Example:
$q = DB::table('orders')->where('status', 'active');
$sql = $q->toSql();
dd($q);


This will result in an SQL query in a string form.

4. DB::raw() for Complex Queries

if you want to use direct SQL queries in Laravel then you can use DB::raw.

For example: 
$q = DB::raw('SELECT * FROM users WHERE status = ?', ['active']);
dd($q);

By using DB::raw query you can directly pinpoint the exact cause of the error immediately.


Conclusion
These SQL debugging techniques help you save a lot of time in fixing the SQL query issues and
pinpointing the exact issue.Also, these will make sure all queries are executed and generated properly without issue.

Friday, 13 August 2021

Laravel session driver file or database


 Laravel Session Driver database

To use the session driver database we need to make the following changes.

Updated .env file as follows:


SESSION_DRIVER=database


Make sure session_driver is set  config/session.php

'driver' => env('SESSION_DRIVER', 'database'),


Now run the command and create a session migration  


php artisan session:table


The above command will create a migration of the session table.

 To create a session table we need to run the laravel artisan command. 


php artisan migrate


You will see the session table structure something


create table sessions

(

  id varchar(255) not null,

  user_id int(10) unsigned null,

  ip_address varchar(45) null,

  user_agent text null,

  payload text not null,

  last_activity int not null,

  constraint sessions_id_unique

  unique (id)

);

If all goes well then laravel sessions will be stored in the database session table. 


Laravel Session Driver File


We need to update the session drive in .env to file 

SESSION_DRIVER=file


That is all we need to do if we want to use the file as a session driver file. 



Wednesday, 28 July 2021

Illuminate\Session\TokenMismatchException in vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken


Issue Reason:

In Laravel when we submit any form or try to run any Ajax request then we must
need to add csrf_token() if we do not add this security token in our requests then 
laravel throws the security error

TokenMismatchException


Form Submission

Add this hidden input security _token field see below.
<input type="hidden" name="_token" value="{{ csrf_token() }}">

Ajax Request
On ajax post or get requests add a header before running ajax request. See below
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });




Disable TokenMismatchException using $except array :
We can disable token check/verifying in laravel but it is not recommanded at all.
Please go to the file  
/app/Http/Middleware/VerifyCsrfToken.php

here you will find an except array see below

protected $except = [
    '/',
];

Add a request in an array that you want to bypass without any security check.





Monday, 26 July 2021

Laravel Fatal error: Class 'StdClass' not found

In Laravel or php when we use to create a generic empty class, especially in Laravel then we need to include the namespace of stdclass.


For example:
// create a new object.
$dataObj = new stdClass();


If we run the above code in Laravel then we will get the error message


Laravel Fatal error: Class 'StdClass' not found


Solution:
On the top of the page Include


use \stdClass


Also if we add a backslash something like below


$Obj = new \stdClass();


In either of the above cases, it will work without any issue.

Laravel csrf token mismatch for ajax post request

Error "CSRF Token Mismatch" commonly occurs if tokens do not match in both sessions and sent , and received requests.CSRF token he...