Laravel order by relation column with example

Explore examples demonstrating the use of Laravel’s orderBy method with relationship columns across various versions.

In this post, we focus on examples to use Laravel order by relation column. There are many different ways to achieve it.

Below are some examples that demonstrate the usage of Laravel‘s orderBy method with relationship columns. These examples can be applied in Laravel versions 5, 6, 7, 8, 9, and 10.

Example 1: Ordering by a BelongsTo Relationship Column

Consider the scenario where you have a "User" model that belongs to a "Role" model. You can use the orderBy method to sort the users based on the role name in ascending order.

$users = User::with(['role' => function ($q) {
    $q->orderBy('name');
}])->get();

You can use the same code for descending order by adding 'desc' argument to orderBy method as follows,

$users = User::with(['role' => function ($q) {
    $q->orderBy('name', 'desc');
}])->get();

For above example to work properly, you have to define belongsTo relationship of "Role" model inside the "User" model as follows,

public function role(): BelongsTo
{
    return $this->belongsTo(Role::class, 'role_id', 'id');
}

Example 2: Using inner join with relation table

For above scenario, where “User” model that belongs to “Role” model, you can use join method to perform user sorting based on role name as follows,

$users = User::select('*')
                 ->join('roles', 'users.role_id', '=', 'roles.id')
                 ->orderBy('roles.name', 'asc');

As above example, you need to replace the second argument of orderBy method to 'desc' for sort records in descending order. There is no need of any relationship required for this query.

Example 3: Using sortBy() and sortByDesc() methods

You can use sortBy() and sortByDesc() methods to order the records for the same scenario as follows,

$users = User::get()->sortBy(function($query){
    return $query->role->name;
})->all();

In above example, it first get the users collection from the database and then sort them by the provided relation column. For these methods, you have to define belongsTo relationship in "User" model.

You can use sortByDesc() method same as above.

Example 4: Using subquery and whereColumn method

You can also use subqueries to sort records. For the above scenario, you can use subqueries as follows,

$users = User::select('*')
    ->orderBy(Role::select('name')
        ->whereColumn('roles.id', 'users.role_id')
    );

In above example, we have we used subquery from roles table using whereColumn method to get the name of the role of each row of users table. After getting the role name, we used orderBy method to achieve the sorted records.

For sorting records in descending order, you can use the above example with orderByDesc method.

You can use this example, without defining belongsTo relationship in model.

These are some useful examples to order records based on relationship model in Laravel.

Using Laravel to upload a file

Learn how to handle file uploads in Laravel, including validations and best practices.

Uploading a file in any programming is a challenge. In this post, we focus on uploading a file and some validations to use with file upload using Laravel.

To upload a file using Laravel, you can follow these steps:

Create a new form in your Laravel view with an input field for the file:

<form method="POST" action="{{ route('file.upload') }}" enctype="multipart/form-data">
    @csrf

    <input type="file" name="file">

    <button type="submit">Upload</button>
</form>

In above code, we have added file.upload route as an action of the form. So, we need to define this route in routes/web.php file. This route should point to the controller method that will handle the file upload.

The following code will define a new route in your routes/web.php file:

Route::post('/file/upload', [App\Http\Controllers\FileController::class, 'upload'])->name('file.upload');

Above code has defined a route, which points to the upload method of the FileController. So, create a new controller FileController and method upload inside that to handle the file upload as follows:

class FileController
{
    public function upload(Request $request)
    {
        // Validate the uploaded file
        $request->validate([
            'file' => 'required|file|max:1024', // limit file size to 1 MB
        ]);

        // Store the uploaded file in the storage/app/public directory
        $path = $request->file('file')->store('public');

        // Generate a URL for the uploaded file
        $url = Storage::url($path);

        // Redirect back with a success message
        return back()->with('success', 'File uploaded successfully: ' . $url);
    }
}

In the upload() method, we first validate that the uploaded file meets our requirements. So, we have added some validations for our file. These validations are as follows:

required:

The field under this validation must be present in the input data and must not empty. A field is “empty” if it meets one of the following criteria:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

file:

The field under this validation must be a successfully uploaded file.

max:1024:

The field under this validation must be less than or equal to a 1024 bytes. Here, 1024 is value of file size. You can change it according to your requirements.

We then use the store() method on the uploaded file to store it in the storage/app/public directory. This directory is publicly accessible, so we can generate a URL for the file using the url() method on the Storage facade. Finally, we redirect back to the form with a success message that includes the URL of the uploaded file.

You can now test the file upload functionality by navigating to the form and selecting a file to upload. If the file meets the validation requirements, it will be uploaded and a success message will be displayed. You can then access the uploaded file at the generated URL.

Detecting Bugs in PHP Code with PHPStan: A Static Analysis Tool

Learn how to detect bugs early in your PHP codebase using PHPStan, a powerful static analyzer. Improve code quality with practical tips and examples.

Writing clean, bug-free code is a goal for every developer — but manual testing and reviews aren’t always enough. That’s where static analysis tools like PHPStan come in. PHPStan helps you catch bugs in your PHP code without executing it. By analyzing your source files, it detects potential issues before they ever become runtime errors.

In this article, we’ll explore what PHPStan is, how it works, and how you can integrate it into your PHP projects to improve code quality.

What is PHPStan?

PHPStan is a static analysis tool specifically designed for PHP. It scans your codebase and finds problems such as:

  • Type mismatches
  • Undefined variables or methods
  • Dead or unreachable code
  • Incorrect method calls

Unlike traditional debuggers, PHPStan doesn’t execute your code — it reads and analyzes your PHP files directly, looking for structural or logical inconsistencies based on static rules.

Why Use PHPStan?

Here are a few reasons to integrate PHPStan into your development workflow:

  • Early bug detection: Spot bugs before running the code.
  • Improved code quality: Enforce strict typing and coding standards.
  • Reduced runtime errors: Catch potential issues during development.
  • Better refactoring: Safely restructure code with confidence.

PHPStan becomes especially powerful when used alongside modern PHP features like type hints, union types, and generics.

Getting Started with PHPStan

Installing PHPStan is very easy. You can install it in your project through composer:

$ composer require --dev phpstan/phpstan

This installs PHPStan as a development dependency.

Running PHPStan

We can now run PHPStan from the base directory of our project. To analyze your code, use the following command:

$ vendor/bin/phpstan analyze src

Replace src with the directory containing your PHP files.

A breakdown of this command:

  • vendor/bin/phpstan is the executable
  • analyze tells PHPStan to analyze all files in the given directories
  • src is the directory we want to analyse

Try running this in your own project and see what kind of potential errors are living in your codebase.

By default, PHPStan analyzes the code with a conservative level of strictness. However, you can make it more strict using levels from 0 (lenient) to 8 (strictest):

vendor/bin/phpstan analyse src --level=5

Configuration with phpstan.neon

For more control, you can create a phpstan.neon configuration file in your project root:

parameters:
    level: 5
    paths:
        - src
        - app
    ignoreErrors:
        - '#Call to an undefined method.*#'

This allows you to customize which folders to analyze, define rules to ignore, and adjust the strictness level.

Common Issues Caught by PHPStan

PHPStan can detect a wide range of issues:

  • Calling methods or accessing properties that don’t exist.
  • Passing the wrong type of arguments to a function or method.
  • Returning values of the wrong type.
  • Forgetting to return a value in non-void functions.
  • Using undefined variables.

These issues often lead to hard-to-find bugs in production. Catching them early saves time and effort.

Integrating PHPStan into CI

To make PHPStan even more effective, integrate it into your CI/CD pipeline. This ensures code is analyzed automatically on every push or pull request, helping maintain a high standard across your team.

For most of my personal projects, I use TravisCI. Since we’ve included PHPStan as a dev-dependency in our composer.json file we just have to add the PHPStan executable to the scripts that the CI-software needs to run.

For TravisCI, this means just changing the default script in a .travis.yml like this:

language: php
php:
  - '8.0'
install: composer install

# Simply add these lines
script:
    - vendor/bin/phpunit
    - vendor/bin/phpstan analyse src tests --level=5

The default script that TravisCI runs for PHP projects is phpunit. Now we’ve added PHPStan to it. If PHPStan finds any errors within your project, the build will fail.

Similarly, in GitHub Actions:

- name: Run PHPStan
  run: vendor/bin/phpstan analyse --level=5

Conclusion

PHPStan is a must-have tool for modern PHP development. It helps you catch bugs early, write cleaner code, and reduce technical debt over time. Whether you’re maintaining a legacy project or starting a new one, integrating PHPStan into your workflow is a smart move.

What Are ORM Frameworks? A Beginner’s Guide

Understand what ORM (Object-Relational Mapping) frameworks are, how they work, and why they are essential in modern web development.

ORM is a short form of Object Relational Mapping. ORM framework is written specifically in OOP (object-oriented programming) language (like PHP, C#, Java, etc…). It is like a wrapper around a relational database (like MySQL, PostgreSQL, Oracle, etc…). So, ORM is basically mapping objects to relational tables.

What does an ORM framework do?

The ORM framework generates objects (as in OOP) that virtually map the tables in a database. So, any programmer could use these objects to interact with the database without writing an optimized SQL code.

For example:

We have 2 tables in a database:

  • Products
  • Orders

The ORM framework would create 2 objects corresponding to the above tables (like products_object and orders_object) with little configuration, which will handle all the database interactions. So, if you want to add a new product to the products table, you would have to use the products_object and save() method like below,

product = new products_object("Refrigerator","Electronics");
product.save();

You can see, how much easier an ORM framework can make things. No need to write any SQL syntax. And the application code would be very clean.

Some other advantages of using ORM frameworks

1. Syncing between OOP language and the relational database data types is always creating a problem. Sometimes variable data types have to be converted properly to insert into the database. A good ORM framework will take care of these conversions.

2. Using an ORM will create a consistent code base for your application, because it is not using any SQL statements in the code. This makes it easier to write and debug any application, especially if more programmers are using same code base.

3. ORM frameworks will shield your application from SQL injection attacks since the framework will be filtering the data before any operation in the database.

4. Database Abstraction; Switching databases for the application is easier as, ORM will take care of writing all the SQL code, data type conversions etc …

When to use an ORM framework?

An ORM framework becomes more useful as the size and complexity of the project increases. An ORM framework may be overkilling an application on a simple database with 5 tables and 5-6 queries to be used for the application.

Consider the use of ORM when:

  • 3 or more programmers are working on an application.
  • Application database consists of 10+ tables.
  • The application is using 10+ queries.

About 80-90% of application queries can be handled by the ORM generated objects. It is inevitable that at some point straight SQL query is required, which can’t be handled by ORM generated objects.

In fact, ORM frameworks often have their own *QL query language that looks a lot like SQL. Doctrine, a popular PHP based ORM framework has DQL (Doctrine Query Language) and the very popular Hibernate (used in the Java and .Net world) has HQL. Going even further, Hibernate allows writing straight SQL if need be.

ORM Frameworks for PHP programmers

  • CakePHP, ORM, and framework for PHP 5
  • CodeIgniter, a framework that includes an ActiveRecord implementation
  • Doctrine, open source ORM for PHP 5.3.X
  • FuelPHP, ORM, and framework for PHP 5.3. Based on the ActiveRecord pattern.
  • Laravel, a framework that contains an ORM called “Eloquent” an ActiveRecord implementation.
  • Maghead, a database framework designed for PHP7 includes ORM, Sharding, DBAL, SQL Builder tools etc.
  • Propel, ORM and query-toolkit for PHP 5, inspired by Apache Torque
  • Qcodo, ORM, and framework for PHP 5
  • QCubed, A community-driven fork of Qcodo
  • Redbean, ORM layer for PHP 5, creates and maintains tables on the fly
  • Yii, ORM, and framework for PHP 5. Based on the ActiveRecord pattern.
  • Zend Framework, a framework that includes a table data gateway and row data gateway implementations. ZendDb

Alternative of PHP Excel for Excel Reading and Writing

Explore modern, efficient PHP libraries to read and write Excel files as alternatives to the deprecated PHP_Excel. Supports .xls, .xlsx, CSV, and more.

Working with Excel files is a common requirement in many PHP applications, especially for tasks like data import/export, reporting, and analysis. In the past, the go-to library for handling Excel files was PHPExcel, but it has since been deprecated and replaced by more efficient and actively maintained alternatives.

Whether you’re looking to read data from .xls or .xlsx files, write spreadsheet data, or handle both tasks seamlessly, this guide explores a wide range of libraries that offer reliable and modern solutions for Excel file manipulation.

Writing Excel using PHP

Reading Excel

Reading and Writing Excel

  • Ilia Alshanetsky’s Excel extension now on github (xls and xlsx, and requires business libXL segment)
  • spout OfficeOpenXML (xlsx) and CSV
  • PHP’s COM extension (requires a COM empowered spreadsheet program, for example, MS Excel or OpenOffice Calc running on the server)
  • SimpleExcel Claims to read and compose MS Excel XML/CSV/TSV/HTML/JSON/and so forth arranges

Another C++ Excel expansion for PHP, however you’ll have to manufacture it yourself, and the docs are really meager with regards to attempting to discover what usefulness (I can’t discover from the site what groups it bolsters, or whether it peruses or composes or both…. I’m speculating both) it offers is phpexcellib from SIMITGROUP.

All case to be quicker than PHPExcel from codeplex or from github, however (except for COM, PUNO Ilia’s wrapper around libXl and spout) they don’t offer both perusing and composing, or both xls and xlsx; might never again be upheld; and (while I haven’t tried Ilia’s expansion) just COM and PUNO offers the same level of control over the made exercise manual.

Source: http://stackoverflow.com/questions/3930975/alternative-for-php-excel