Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Matrices Laravel Package

graham-campbell/matrices

A lightweight PHP library for creating and manipulating matrices, with a clean API for common matrix operations. Easy to integrate into Laravel or standalone PHP projects for straightforward matrix math.

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package with Composer:

composer require graham-campbell/matrices

The core library is framework-agnostic. Start by reading the package README, then inspect src/Matrix.php and the test suite to confirm exact method names and return types for your installed version. The main entry point is the Matrix class.

Minimal first use case:

use GrahamCampbell\Matrices\Matrix;

$matrix = new Matrix([
    [1, 2],
    [3, 4],
]);

$determinant = $matrix->determinant(); // -2
$inverse = $matrix->inverse();

$transposed = $matrix->transpose();

A good first real use case is a small, fixed-size transformation or 2×2/3×3 linear algebra calculation inside a service class. Build the matrix from a validated nested array, perform one operation, and assert the result in a unit test before introducing it into business logic.

For Laravel, the core math API works without the framework. If you want the package’s Laravel integration, check composer.json for extra.laravel provider/facade metadata and rely on package discovery where supported, or register the service provider manually in config/app.php. No configuration should be required for basic matrix operations.

Implementation Patterns

Treat Matrix as a value object. Construct it at the boundary of your application after validating the input shape:

$rows = $request->input('matrix');

if (!is_array($rows) || count($rows) === 0) {
    throw new InvalidArgumentException('Matrix must be a non-empty array.');
}

$width = count($rows[0]);
foreach ($rows as $row) {
    if (!is_array($row) || count($row) !== $width) {
        throw new InvalidArgumentException('Matrix must be rectangular.');
    }
}

$matrix = new Matrix($rows);

Encapsulate matrix work behind a small application service rather than scattering Matrix calls through controllers:

final class MatrixCalculator
{
    public function invert(array $rows): array
    {
        return (new Matrix($rows))->inverse()->toArray();
    }

    public function isInvertible(array $rows): bool
    {
        return (new Matrix($rows))->determinant() != 0;
    }
}

Use chainable operations for readable pipelines when the package returns new Matrix instances:

$result = (new Matrix($a))
    ->transpose()
    ->multiply(new Matrix($b))
    ->add(2);

Use determinant checks before inversion in workflows where singular input is expected:

$matrix = new Matrix($rows);

if ($matrix->determinant() == 0) {
    throw new DomainException('Matrix is singular.');
}

$inverse = $matrix->inverse();

For linear-system style work, keep the matrix construction and validation in one place, and keep the solver in another. This makes it easy to swap the underlying library later.

In Laravel, inject your wrapper service into controllers, jobs, or actions instead of calling the package directly. If the package registers bindings, use them; otherwise bind your own MatrixCalculator or factory in a service provider. This keeps the third-party API out of your domain code.

Test with small known matrices before using larger inputs. For example, assert that a 2×2 inverse multiplied by the original is approximately the identity matrix.

Gotchas and Tips

  • Dimension mismatches are the most common failure. Addition and subtraction require equal dimensions; multiplication requires the left matrix’s column count to match the right matrix’s row count. Validate early and wrap package exceptions with domain-specific messages.
  • Square-only operations. Determinant, inverse, adjoint, and cofactor calculations generally require square matrices. Check dimensions before calling them.
  • Singular matrices cannot be inverted. A zero determinant means the inverse is undefined. Guard against this explicitly instead of relying on an exception deep in a request.
  • Floating-point comparisons are unreliable. Avoid strict === comparisons on computed matrix values. Compare nested arrays with an epsilon tolerance.
  • Integer inputs may produce float outputs. Inversion and division-heavy operations commonly return floats. Normalize or round only at the presentation boundary, not in the middle of calculations.
  • Confirm mutability. Check whether operations mutate the original matrix or return a new one in your installed version. Treat results as new values and assign them explicitly to avoid surprising aliasing.
  • Performance is for small dense matrices. Matrix inversion and multiplication are typically cubic-time. Do not use this package for large sparse systems, recommendation engines, or high-volume numerical workloads; use a dedicated numerical library or extension instead.
  • Laravel discovery can be stale. If the provider or facade is not registered, run composer dump-autoload and clear cached config with php artisan config:clear. Check the package’s composer.json for the exact provider class and alias.
  • Debug with small arrays. When a result looks wrong, dump the input and output as nested arrays and reproduce with a 2×2 case. Most issues are shape errors or an accidental scalar/matrix mix-up.
  • Keep an extension boundary. Wrap the package in your own factory or calculator service, add validation there, and avoid editing vendor code. That makes upgrading or replacing the library much easier.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel