Wednesday, 28 July 2021

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


Laravel is a strong PHP framework that comes with strong security features built in. CSRF (Cross-Site Request Forgery) protection is one of the most important security features in Laravel. However, developers often run into the TokenMismatchException error when they send AJAX requests or fill out forms. This error happens most of the time when the CSRF token that is needed is missing or not valid.

This article will explain what the Laravel TokenMismatchException error is, what usually causes it, and how to fix it in Laravel apps.

Monday, 26 July 2021

Laravel Fatal error: Class 'StdClass' not found

When working with PHP and the Laravel framework, developers often create simple objects for temporary data storage. One common way to do this is by using the stdClass object in PHP. However, many developers encounter the error “Laravel Fatal error: Class 'StdClass' not found” while trying to create a generic object.

This issue usually occurs because Laravel follows strict namespace rules, and if the stdClass namespace is not referenced correctly, PHP cannot locate the class. In this article, we will understand this error, explore the common causes, and learn different ways to fix it.

Understanding the Error

Monday, 19 July 2021

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

Understanding the Error.

When working with Laravel’s Eloquent ORM, developers sometimes face issues when updating records in the database. One common mistake occurs when a non-static method is called statically. This usually results in unexpected behavior or the update query not working properly.

In Laravel, methods like update() belong to either a model instance or a query builder. Calling them directly using the model class without defining a query condition can cause errors or prevent the database update from executing.

This issue often appears when developers try to update a record using Product::update() directly. Since update() requires a query builder instance or a model instance, Laravel cannot determine which record to update.

Understanding how Eloquent works with model instances and query builders is essential. Once developers follow the correct approach for selecting records before updating them, this error can be easily resolved.

Sunday, 18 July 2021

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

When importing large MySQL database files, you may encounter the “MySQL server has gone away” or “Packet too large” error. This usually happens when the file size exceeds the server’s allowed packet limit.

This issue is common during database migrations, backups, or restoring large .sql dump files. If your MySQL configuration is not optimized for large imports, the process will fail midway.

By default, MySQL limits the size of data packets it can process at once. When you try to upload a database file larger than this limit, the server automatically stops the operation.

Understanding this error is essential for developers working with large databases in local environments like XAMPP or on live servers. Proper configuration can easily resolve the issue.

Common Causes

Below are the main reasons why this MySQL error appears:

Low max_allowed_packet Value
The default max_allowed_packet size in MySQL (especially version 5.6) is only 4MB. Large SQL dump files exceed this limit.

Large Database Import File
When importing big .sql files containing heavy data tables, images (BLOBs), or large inserts, MySQL cannot process them due to packet restrictions.

Server Configuration Not Updated
Sometimes configuration files like my.cnf or my.ini are not properly updated, or the MySQL service is not restarted after changes.

Wednesday, 14 July 2021

Laravel Change Timezone

Laravel uses UTC (Coordinated Universal Time) as the default timezone in every fresh installation. This ensures consistency when storing timestamps in the database.

However, many applications require a local time zone to correctly display dates and times to users. Without proper configuration, time-related data may appear incorrect.

The timezone setting directly affects Carbon instances, logs, scheduled tasks, and timestamps created by Eloquent models. That is why configuring it properly is important.

If your application serves users in a specific country, such as Pakistan, setting the correct timezone, like Asia/Karachi, ensures accurate time display across the system.

Common Causes.

Time zone-related issues in Laravel usually occur due to the following reasons:

  • The default UTC value is never changed after installing Laravel, causing a mismatch between server time and user time.
  • Developers update the timezone in config/app.php but forget to clear the configuration cache, so Laravel continues using the old cached value.
  • The .env file does not contain the correct APP_TIMEZONE variable, or the value is misspelled, which prevents Laravel from applying the intended timezone.

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, or Europe/London).

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


Step 2: Clear configuration caches:

After making changes, clear the configuration cache to apply updates immediately. Run the following commands in your project root directory:

php artisan cache:clear
php artisan config:clear

If you are using queues or scheduled tasks, restart them to ensure the new timezone is applied.


Additional considerations:
Environment variable: For flexibility across environments, consider setting the time zone using an environment variable:

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

Conclusion.

Changing the timezone in Laravel is a small configuration step, but it plays a critical role in maintaining accurate date and time records. Incorrect time zone settings can lead to reporting errors and user confusion.

Using UTC for storage and converting time zones for display is generally considered best practice. However, setting the application timezone correctly ensures consistent behavior across logs, tasks, and system operations.

Leveraging environment variables provides better control and flexibility when deploying to multiple environments. It also keeps your configuration clean and manageable.

By carefully updating the timezone setting and clearing the configuration cache, you can ensure your Laravel application handles time data accurately and professionally across all features.

Tuesday, 6 July 2021

Change laravel web application default locale dynamically

Understanding the Error

Changing the default locale dynamically in a Laravel web application means updating the language of the application at runtime. Instead of using a fixed language from config/app.php, we switch it based on user selection.

Sometimes developers face issues where the language does not change even after updating the session. This usually happens due to missing middleware registration or incorrect session handling.

Another common confusion is that the locale changes only for one request and resets on refresh. This happens when the session is not properly stored or middleware is not applied in the web group.

Understanding how Laravel handles localization through App::setLocale() and session storage is important. Once configured correctly, the locale will persist across all requests.

Common Causes

Errors while changing locale dynamically usually occur due to the following reasons:

  • Middleware not registered in Kernel.php.
  • The session is not started, or the session driver is misconfigured.
  • Incorrect route parameter handling or mismatch in variable names.

How to Fix the Error

Step: 1 

Create a proper localization middleware and ensure App::setLocale() is called when the session has a locale value. 

<?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 the locale variable in the session, and on each request, it will set the application locale variable.

Step: 2

Register the middleware inside the web middleware group in app/Http/Kernel.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

Ensure the session is working correctly by checking the .env file (SESSION_DRIVER=file or database).

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 the locale variable in two languages: English and French. So requests changeLocale/en and changeLocale/fr will set the locale value.

Step: 4

HTML code that will allow us to change language and hit the 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 the locale key in the session, and based on that, it will run the route, and after running the route, it will set the session key locale value.

Conclusion

Dynamically changing the Laravel locale is a simple and professional approach to building multilingual applications. By using middleware and session storage, we can control the application language globally.

The key concept is storing the selected language in a session and applying it on every request using middleware. Without middleware, the locale will not persist across pages.

This method is clean, reusable, and scalable for larger projects. It works perfectly for applications that support multiple languages.

Once properly implemented, users can switch languages smoothly without affecting application performance or structure.

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 is a common issue encountered by Laravel developers. It usually occurs when Laravel is unable to locate a specific class due to namespace misconfiguration or incorrect references in your controller or routes. Since Laravel relies heavily on the PSR-4 autoloading standard, even a minor mismatch in the namespace or file structure can trigger this error.

This error often appears when developers try to call a class that either does not exist or is incorrectly referenced in the code. It can occur in controllers, middleware, or even route definitions. The framework expects every class to follow a consistent namespace and folder structure. Any deviation from this standard may lead to the “class not found” issue.

Beginners often face this error when copying code from tutorials or external sources without adjusting namespaces. Laravel’s autoloader is strict, so it cannot automatically resolve classes outside the declared namespace. Understanding why the framework cannot find the class is the first step toward a proper fix.

In addition, the error may also appear due to missing or outdated autoload files. Laravel uses Composer to manage dependencies and autoload classes. If Composer’s autoload is not updated after adding or modifying classes, Laravel may fail to locate them, resulting in this error.

Common Causes

This error can arise from several common mistakes or oversights in Laravel development. Some of the most frequent causes include:

Incorrect Namespace Declaration
If the namespace declared at the top of your controller does not match the folder structure, Laravel will not be able to locate the class. For example, a controller inside App\Http\Controllers must declare the namespace App\Http\Controllers.

Missing or Wrong Use Statements
When referencing other classes, such as models, helpers, or the App class, incorrect or missing use statements can trigger the error. Always ensure the class you are calling is properly imported at the top of your file.

Typographical Errors
Even small typos in class names, namespaces, or route definitions can prevent Laravel from finding the class. Laravel is case-sensitive, so YourController and yourcontroller are treated differently.


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


  1. Check for Typographical Errors:

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


Conclusion

The "Class 'App\Http\Controllers\App' not found" error is a frequent challenge for Laravel developers, especially those new to the framework. Understanding the root causes, such as namespace mismatches, missing use statements, or typographical errors, is essential for resolving them quickly.

By ensuring correct namespace declarations, proper use statements, accurate route references, and refreshing Composer’s autoload, most instances of this error can be fixed efficiently. Developers should also maintain consistent file naming and folder structure to avoid similar issues in the future.

Regularly checking your code for typos and following Laravel’s PSR-4 standards can prevent this error from recurring. With these practices, you can save time, reduce debugging frustration, and keep your Laravel projects running smoothly.

Ultimately, this error is more of a configuration oversight than a critical bug, and learning to handle it reinforces good coding practices in Laravel development.

.htaccess not working even though allowoverride is enabled

You're not the only one who has had the annoying problem with Apache where your file doesn't work even after you enable it. You'...