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

Monday, 16 October 2023

Optimizing Laravel Models: How to Append Custom Attributes

In Laravel's Eloquent ORM, you can easily append attributes to a model that don't exist in the database but can be derived from existing attributes. These are often called "accessors."


Here's how to append an attribute to a model using an accessor:


  1. Define an Accessor:

To define an accessor, create a get<AttributeName>Attribute method on your model where <AttributeName> is the studly cased name of the column you wish to access.


    2. Use the $appends Property:

If you want the attribute to be included in the model's array or JSON representation, you should add it to the $appends property on the model.


Example:

Suppose you have a User model with first_name and last_name columns in the database, but you want to easily retrieve the user's full name.


namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class User extends Model

{

    // Attributes to be appended to the model's array or JSON representation

    protected $appends = ['full_name'];


    // Accessor to get the full name

    public function getFullNameAttribute()

    {

        return $this->first_name . ' ' . $this->last_name;

    }

}

Now, when you convert a User model instance to an array or JSON, it will include the full_name attribute:

$user = User::find(1); return $user->toArray();


output

[
 'id' => 1, 
'first_name' => 'John', 
'last_name' => 'Doe', 
'full_name' => 'John Doe', 
// ... other attributes ... 
]

Remember, accessors will not affect how data is stored in your database, only how it's represented when you access it using Eloquent.


Saturday, 28 January 2023

How do I connect Laravel 7 to Microsoft SQL Server?



Integrating Laravel 7 with Microsoft SQL Server can significantly enhance your web application's capabilities, allowing it to leverage the robust features of one of the most powerful database management systems. This guide provides a concise and SEO-friendly overview of the steps required to establish a connection between Laravel 7 and Microsoft SQL Server, ensuring your application can interact with your database seamlessly.
Pre-requisites

Before proceeding, ensure you have Laravel 7 installed on your system. You also need access to a Microsoft SQL Server instance. The SQL Server's version should be compatible with the PHP version you're using in your Laravel project.


Step 1: Install the Required Driver


To connect to Microsoft SQL Server from Laravel, you need the correct PHP driver installed on your server. For Windows, you can use the SQLSRV extension. On Linux, you'll need to install the FreeTDS driver as Laravel uses PDO for database connections.Windows: Download and enable the SQLSRV extension in your php.ini file.
Linux: Install FreeTDS and the PHP PDO extension for SQLSRV (pdo_sqlsrv).

Step 2: Configure Your Laravel Project

After installing the necessary drivers, the next step is to configure your database connection in Laravel. This involves editing the .env file and the config/database.php file in your Laravel project..env File: Locate your .env file at the root of your Laravel project. Add or modify the following lines to match your SQL Server's credentials:

DB_CONNECTION=sqlsrv
DB_HOST=server_host
DB_PORT=server_port
DB_DATABASE=databasename
DB_USERNAME=databaseusername
DB_PASSWORD=databasepassword

config/database.php: Open this file and scroll down to the connections array. Ensure that the sqlsrv connection parameters match the ones you specified in your .env file.

Step 3: Test the Connection

To verify that your Laravel application can successfully connect to Microsoft SQL Server, you can use Laravel's built-in database tools. Running a migration is a simple way to test this:

php artisan migrate


If the migration runs successfully without errors, your Laravel application is now connected to Microsoft SQL Server.
Troubleshooting

If you encounter any issues, check the following:Ensure the SQL Server is running and accessible.
Verify your PHP driver installation and configuration.
Double-check your .env and config/database.php settings.

Additionally

We can download SQL Server extension from here download-drivers-php-sql-server

On windows if your system is 32 bit or 64 bit then download both extensions accordingly.

Add sql server extensions in php.ini as follow


For 64 bit system

extension=php_sqlsrv_74_ts_x64.dll
extension=php_pdo_sqlsrv_74_ts_x64.dll

For 32 bit system

extension=php_sqlsrv_74_ts_x86.dll
extension=php_pdo_sqlsrv_74_ts_x86.dll

To verify both extension are installed check php settings using phpinfo

Tuesday, 14 December 2021

Laravel faker package

 

Understanding Laravel Faker

Laravel Faker is an open-source library, seamlessly integrated with Laravel, that provides a convenient way to generate fake, yet realistic data for your database. Whether you need names, addresses, emails, or even more complex data types, Faker has got you covered. It's an essential tool for developers who require a reliable and efficient method to test and demonstrate their applications.

Key Features of Laravel Faker

  1. Diverse Data Types: From basic text data like names and addresses to more complex data like credit card numbers and biographical details, Faker can generate a wide range of data types.


  2. Localization Support: With support for various locales, Faker allows you to generate data that is relevant to specific regions, ensuring that your application is tested with culturally appropriate data.


  3. Customizable Data Generation: Laravel Faker is not just about random data. You can customize the data generation process to fit your specific requirements, ensuring that the generated data aligns closely with real-world scenarios.


  4. Ease of Integration: Integrating Faker with Laravel is straightforward. It works seamlessly with Laravel's seeding mechanism, making it a hassle-free addition to your development toolkit.


  5. Efficient Testing: By using Faker for generating test data, developers can ensure thorough testing of their applications, leading to more reliable and robust software.

How Laravel Faker Enhances Development

  1. Improved Testing: With realistic data sets, developers can better simulate real-world scenarios, leading to more effective and comprehensive testing.


  2. Time-Saving: Manually creating test data can be time-consuming. Faker automates this process, allowing developers to focus on more critical aspects of their projects.


  3. Data Privacy Compliance: Using real user data for testing can raise privacy concerns. Faker eliminates this issue by providing fictional yet realistic data, ensuring compliance with data protection regulations.


  4. Enhanced Demonstration Capabilities: When showcasing applications to clients or stakeholders, having realistic data is crucial. Faker helps in creating compelling demos with data that looks authentic.


  5. Community Support: Being a popular package in the Laravel ecosystem, Faker has strong community support, providing a wealth of resources and assistance for developers.


Installing Fake Package

To get started we need to install the faker package using the composer package manager.

To install the fake package run the following command

composer require fzaninotto/faker


Generate fake data

Create an instance of the faker package

$faker = Faker\Factory::create();

Using the created instance of the faker package we can generate different fake data 

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