Showing posts with label Laravel Tutorials. Show all posts
Showing posts with label Laravel Tutorials. Show all posts

Tuesday, 17 October 2023

Efficiently Linking Multiple DB Tables to users_profiles in Laravel

Laravel is a heavyweight in the world of PHP frameworks and is becoming more popular among developers because it is elegant and easy to scale. Laravel's ability to handle databases and relationships is something that many people find interesting. How can you easily connect multiple database tables to one table, like users_profiles? Check out this guide for a full walkthrough.

Monday, 16 October 2023

Optimizing Laravel Models: How to Append Custom Attributes

You can easily add attributes to a model in Laravel's Eloquent ORM that aren't in the database but can be made from existing attributes. People often call these "accessors."

This is how to use an accessor to add an attribute to a model:

  1. What is an Accessor?

In Laravel, you can define an accessor by making a method on your Eloquent model that follows this naming pattern:

get<AttributeName>Attribute

Sunday, 29 January 2023

Laravel Socialite with Google Account

Using Google Social Login in Laravel is a great way to make it easier for users to log in and make their experience better. Users can log in with just one click using their Google account instead of making new accounts and remembering passwords.

Laravel has an official package called Laravel Socialite that makes it very easy to add social login providers like Google, Facebook, GitHub, and Twitter.

This guide will show you step-by-step how to set up Google Login in Laravel using Socialite. It will cover making a Google app, getting credentials, and setting up Laravel.

Why Use Google Social Login in Laravel?

Before diving into the implementation, let's understand why developers prefer Google login.

Saturday, 28 January 2023

Laravel Rest API Localization

Localization is a key part of modern web apps, especially if your users are from different parts of the world and speak different languages. When you make APIs with Laravel, you often need to send back responses in more than one language, depending on what the user wants. Laravel has a great localization system that makes it simple to translate the content of your app.

Using middleware is one of the best ways to add REST API localization to Laravel. Middleware lets you stop incoming API requests, check for language preferences, and set the application language on the fly before the request gets to the controller.

Tuesday, 14 December 2021

Laravel faker package

When making web apps, developers often need a lot of test data. Making this data by hand can take a long time and not be very useful. This is when Laravel Faker comes in very handy. Laravel Faker is a useful library that lets developers make fake data that looks real for testing, development, and showing off.

Laravel's database seeding system works perfectly with Faker, which makes it easy to fill databases with sample records like names, emails, addresses, and more. Without using real user data, developers can quickly simulate real-world data.

Thursday, 25 November 2021

How do I disable error reporting in Laravel

Understanding the Error

When you run a Laravel app in development mode, it shows you detailed error messages whenever something goes wrong. These mistakes include stack traces, file paths, and debugging information that help developers find and fix problems quickly. But showing such detailed mistakes in a production environment can be very dangerous for security.

Visitors shouldn't be able to see technical error details in a production environment. The app should show a generic error page instead and log the real error internally. This keeps sensitive system information hidden from people who use the system.

Wednesday, 10 November 2021

What is Laravel stub?

Laravel is a strong PHP framework that has a lot of tools to make development easier. Laravel Stubs is one of these helpful tools that helps developers automatically create structured code files. When Laravel makes new classes, models, controllers, migrations, and many other things through Artisan commands, it uses stub files as templates.

Wednesday, 20 October 2021

Set Base URL for Assets in Laravel Applications

Setting the base URL for assets in a Laravel app is an important step to make sure that files like CSS stylesheets, JavaScript files, fonts, and images load correctly. Assets are very important for how well and how good a web app looks. Users may see broken layouts, missing images, or scripts that don't work if the asset paths aren't set up correctly.

Laravel makes it easier to manage assets by including helper functions and environment settings. Developers can make sure that the app works well in local development, staging servers, and production environments by setting the base URL correctly.

This guide shows you how to set up the base URL for assets in Laravel, how the .env file affects loading assets, and how to use a Content Delivery Network (CDN) to make things run faster.

Setting or configuring base URLs correctly makes sure that our app can be used in different environments, such as staging and production.

Friday, 13 August 2021

Laravel session driver file or database

Learning about Laravel Session Drivers

Laravel session drivers tell the system where to save session data. Laravel saves session data temporarily when a user interacts with your app so that it can be used again in future requests.

Laravel saves a user's login information in a session when they log into your app, for example. This lets the system know who the user is without them having to log in again on every page.

Using the .env configuration file and the session configuration file, developers can easily change how Laravel stores sessions.

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.

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