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.

Monday, 19 July 2021

Laravel Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically


Reason:
Sometimes DB updates do not work because we are calling non-static methods statically.



We should change your approach to update the Product. We could possibly follow different ways.



Error Code

Product::update([ 'product_sku' => $product_sku,'product_name' => $product_name);


We are calling to update suddenly after the status product but must need to change it to something like

Product::where('id', $product_id)->update([ 'product_sku' => $product_sku

,'product_name' => $product_name);
or
Product::find($id)
->update([ 'product_sku' => $product_sku,'product_name' => $product_name);

Sunday, 18 July 2021

ERROR: SQLSTATE[08S01]: Communication link failure: Got a packet bigger than 'max_allowed_packet' bytes


Reason:
When we use to import bigger size MySQL files then we get such an error.


Possible Solutions:

Please open your mysql terminal and type mysql to get a mysql prompt. In your mysql settings look for the following files.
  1. my.cnf 
  2. my.ini 
Open the above files and update

max_allowed_packet=100M
max_allowed_packet=1000M ; 1GB

After updating the above file in localhost or live server. Please restart the mysql/apache servers. So
that change will reflect. To restart the mysql server please run the following command.

service mysql restart

or you can open up your MySQL console and run the following command

set global max_allowed_packet=1000000000;
set global net_buffer_length=1000000;

The above commands basically, increase and set the max allowed packet size in mysql.

Note:
The default MySQL 5.6. 6 max packet size is 4MB
Also, you can dump the  MySQL file using the below command by mentioning the size
mysql --max_allowed_packet=100M -u root -p database < dump.sql

Wednesday, 14 July 2021

Laravel Change Timezone

Laravel Change Timezone


By default UTC is set as a default timezone in laravel instalaltion.We can change it very easily.









Step 1 : Adjust the configuration:

    
Navigate to the config/app.php file within your Laravel project.




Locate the 
timezone setting.


Replace the default value UTC with your desired timezone string, ensuring it's a valid PHP timezone identifier  (e.g., Asia/Karachi, America/Los_Angeles, Europe/London).

// 'timezone' => 'UTC',
   'timezone' => 'Asia/Karachi',



Step 2:Clear configuration caches:

After changing the timezone we need to run following commands

php artisan cache:clear
php artisan config:clear


These commands will clear all config and other cache.

Additional considerations:

  • Environment variable: For flexibility across environments, consider setting the timezone using an environment variable:

'timezone' => env('APP_TIMEZONE', 'UTC'),
In env file we can define APP_TIMEZONE constant with the required timezone

That's it. If you have any question please feel fee to ask.




Tuesday, 6 July 2021

Change laravel web application default locale dynamically

 To change laravel locale dynamically we can apply different ways.Today I will teach you very easily

and professional way that I use to follow in all my laravel projects.


Step: 1 

Define middleware 

<?php

namespace App\Http\Middleware;

use Closure;
use App;

class Localization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($requestClosure $next)
    {
        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}


you can see I have defined  Localization  middleware.Which will check  locale variable in session 

and on each request it will set application locale variable.



Step: 2 

Include middle in kernal.php php 

/**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\Localization::class,
        ],

        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];


 \App\Http\Middleware\Localization::class,


step: 3

Set locale using session variable.For example I have used in web.php

Route::get('changeLocale/{locale}',function($lang){
    if ($lang == "fr") {
        Session::put('locale', 'fr');
    } else {
        Session::put('locale', 'en');
    }
    return redirect()->back();
});

Here you can see i am setting locale variable in two languages english and french.

So requests changeLocale/en and So changeLocale/fr will set locale value.


step: 4 

html code that will allow use to change language and hit above get request.

<li class="eborder-top">
@if( \Session::get('locale') == "fr" )
<a href="{{ url('/changeLocale/en') }}">
<i class="fa fa-key" aria-hidden="true"></i> English
</a>
@else
<a href="{{ url('/changeLocale/fr') }}">
<i class="fa fa-key" aria-hidden="true"></i> French
</a>
@endif
</li>


Above will check locale key in session and based on that it will run the routed and after

running the route it will set the session key locale value.


For any questions or understanding please do contact !

Monday, 5 July 2021

Class 'App\Http\Controllers\App' not found in laravel

 Understanding the Error:

The "Class 'App\Http\Controllers\App' not found" error typically occurs when there is a namespace misconfiguration or an incorrect use statement within your controller or route definition. Laravel relies on the correct namespace to load classes automatically. Therefore, any discrepancy can lead to this error.

Steps to Resolve the Error:

  1. Check Namespace Declaration: 

  2. Ensure that the namespace declared at the top of your controller matches the directory structure. For a standard Laravel setup, controllers should be within the App\Http\Controllers namespace.


  3. Use Correct Use Statements:

  4. If you're referencing the App class or any other class within your controller, ensure you have the correct use statements at the top of your controller file.


  5. Controller Declaration in Routes:

    When defining routes in web.php or api.php, make sure you reference the controller correctly. Use the fully qualified class name (FQCN), for example,


    App\Http\Controllers\YourController::class.


  6. Composer Autoload:

  7. Sometimes, the error might be due to the autoloader not recognizing the class. Running composer dump-autoload in your terminal can refresh the autoload files and potentially resolve the issue.

  8. Check for Typographical Errors:

  9. A simple typographical error in the class name or namespace can also cause this error. Double-check your spelling and case sensitivity.

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