PHPackages                             spatie/backtrace - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Debugging &amp; Profiling](/categories/debugging)
4. /
5. spatie/backtrace

ActiveLibrary[Debugging &amp; Profiling](/categories/debugging)

spatie/backtrace
================

A better backtrace

1.8.2(2mo ago)433169.4M—1.6%3020MITPHPPHP ^7.3 || ^8.0CI passing

Since Nov 23Pushed 4w ago7 watchersCompare

[ Source](https://github.com/spatie/backtrace)[ Packagist](https://packagist.org/packages/spatie/backtrace)[ Docs](https://github.com/spatie/backtrace)[ GitHub Sponsors](https://github.com/sponsors/spatie)[ Fund](https://spatie.be/open-source/support-us)[ RSS](/packages/spatie-backtrace/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (28)Used By (20)

A better PHP backtrace
======================

[](#a-better-php-backtrace)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1796f9b8b90b626af80ab45b3a184cecbd50684d8fb3a8d8bd97c8c4b01c6ceb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6261636b74726163652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/backtrace)[![Tests](https://github.com/spatie/backtrace/workflows/Tests/badge.svg)](https://github.com/spatie/backtrace/workflows/Tests/badge.svg)[![Total Downloads](https://camo.githubusercontent.com/d118f9e6cd09ea0a38bd7500a1999277e16babc27cd686cedb0677b11734913b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6261636b74726163652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/backtrace)

To get the backtrace in PHP you can use the `debug_backtrace` function. By default, it can be hard to work with. The reported function name for a frame is skewed: it belongs to the previous frame. Also, options need to be passed using a bitmask.

This package provides a better way than `debug_backtrace` to work with a back trace. Here's an example:

```
// returns an array with `Spatie\Backtrace\Frame` instances
$frames = Spatie\Backtrace\Backtrace::create()->frames();

$firstFrame = $frames[0];

$firstFrame->file; // returns the file name
$firstFrame->lineNumber; // returns the line number
$firstFrame->class; // returns the class name
```

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/7d42cdff3071e0532df527af58bdb2fa13d2d2d925ea0c04ea9804af9cf99fa1/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6261636b74726163652e6a70673f743d31)](https://spatie.be/github-ad-click/backtrace)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require spatie/backtrace
```

Usage
-----

[](#usage)

This is how you can create a backtrace instance:

```
$backtrace = Spatie\Backtrace\Backtrace::create();
```

### Getting the frames

[](#getting-the-frames)

To get all the frames you can call `frames`.

```
$frames = $backtrace->frames(); // contains an array with `Spatie\Backtrace\Frame` instances
```

A `Spatie\Backtrace\Frame` has these properties:

- `file`: the name of the file
- `lineNumber`: the line number
- `arguments`: the arguments used for this frame. Will be `null` if `withArguments` was not used.
- `class`: the class name for this frame. Will be `null` if the frame concerns a function.
- `method`: the method used in this frame
- `object`: the object when the frame is in an object context (method call, closure bound to object, arrow function which captured `$this`, etc.). Will be `null` if `withObject` was not used.
- `applicationFrame`: contains `true` is this frame belongs to your application, and `false` if it belongs to a file in the vendor directory. A couple edge cases exist, see "application frames" below.

### Collecting arguments and objects

[](#collecting-arguments-and-objects)

For performance reasons, the frames of the back trace will not contain the arguments of the called functions and the object. If you want to add those, use the `withArguments` and `withObject` methods.

```
$backtrace = Spatie\Backtrace\Backtrace::create()->withArguments()->withObject();
```

#### Reducing arguments

[](#reducing-arguments)

For viewing purposes, arguments can be reduced to a string:

```
$backtrace = Spatie\Backtrace\Backtrace::create()->withArguments()->reduceArguments();
```

By default, some typical types will be reduced to a string. You can define your own reduction algorithm per type by implementing an `ArgumentReducer`:

```
class DateTimeWithOtherFormatArgumentReducer implements ArgumentReducer
{
    public function execute($argument): ReducedArgumentContract
    {
        if (! $argument instanceof DateTimeInterface) {
            return UnReducedArgument::create();
        }

        return new ReducedArgument(
            $argument->format('d/m/y H:i'),
            get_class($argument),
        );
    }
}
```

This is a copy of the built-in argument reducer for `DateTimeInterface` where we've updated the format. An `UnReducedArgument` object is returned when the argument is not of the expected type. A `ReducedArgument` object is returned with the reduced value of the argument and the original type of the argument.

The reducer can be used as such:

```
$backtrace = Spatie\Backtrace\Backtrace::create()->withArguments()->reduceArguments(
    Spatie\Backtrace\Arguments\ArgumentReducers::default([
        new DateTimeWithOtherFormatArgumentReducer()
    ])
);
```

Which will first execute the new reducer and then the default ones.

### Setting the application path

[](#setting-the-application-path)

You can use the `applicationPath` to pass the base path of your app. This value will be used to determine whether a frame is an application frame, or a vendor frame. Here's an example using a Laravel specific function.

```
$backtrace = Spatie\Backtrace\Backtrace::create()->applicationPath(base_path());
```

### Removing the application path from the file name

[](#removing-the-application-path-from-the-file-name)

You can use `trimFilePaths` to remove the base path of your app from the file. This will only work if you use it in conjunction with the `applicationPath` method re above. Here's an example using a Laravel specific function. This will ensure the Frame has the trimmedFilePath property set.

```
$backtrace = Backtrace::create()->applicationPath(base_path())->trimFilePaths());
```

### Application frames

[](#application-frames)

By default, a frame is considered an application frame when the file of the frame is not in the vendor directory. The following edge cases apply:

- Laravel's `artisan` CLI file (generally found in the root of the project) is considered a vendor file and frame
- Statamic's `please` CLI file (generally found in the root of the project) is considered a vendor file and frame

### Getting a certain part of a trace

[](#getting-a-certain-part-of-a-trace)

If you only want to have the frames starting from a particular frame in the backtrace you can use the `startingFromFrame` method:

```
use Spatie\Backtrace\Backtrace;
use Spatie\Backtrace\Frame;

$frames = Backtrace::create()
    ->startingFromFrame(function (Frame $frame) {
        return $frame->class === MyClass::class;
    })
    ->frames();
```

With this code, all frames before the frame that concerns `MyClass` will have been filtered out.

Alternatively, you can use the `offset` method, which will skip the given number of frames. In this example the first 2 frames will not end up in `$frames`.

```
$frames = Spatie\Backtrace\Backtrace::create()
    ->offset(2)
    ->frames();
```

### Limiting the number of frames

[](#limiting-the-number-of-frames)

To only get a specific number of frames use the `limit` function. In this example, we'll only get the first two frames.

```
$frames = Spatie\Backtrace\Backtrace::create()
    ->limit(2)
    ->frames();
```

### Getting a backtrace for a throwable

[](#getting-a-backtrace-for-a-throwable)

Here's how you can get a backtrace for a throwable.

```
$frames = Spatie\Backtrace\Backtrace::createForThrowable($throwable)
```

Because we will use the backtrace that is already available in the throwable, the frames will contain the arguments used in the backtrace as long as the `zend.exception_ignore_args` INI option is disabled (set to `0`) *before* the throwable is thrown. On the other hand, objects will never be included in the backtrace. [More information](https://www.php.net/manual/en/throwable.gettrace.php#129087).

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Freek Van de Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

72

—

ExcellentBetter than 100% of packages

Maintenance91

Actively maintained with recent releases

Popularity74

Solid adoption and visibility

Community39

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~77 days

Total

26

Last Release

68d ago

Major Versions

0.0.1 → 1.0.02020-11-24

PHP version history (3 changes)0.0.1PHP ^7.4|^8.0

1.0.1PHP ^7.3|^8.0

1.7.0PHP ^7.3 || ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (69 commits)")[![rubenvanassche](https://avatars.githubusercontent.com/u/619804?v=4)](https://github.com/rubenvanassche "rubenvanassche (42 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (18 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (12 commits)")[![jivanf](https://avatars.githubusercontent.com/u/25129083?v=4)](https://github.com/jivanf "jivanf (10 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (9 commits)")[![jackbayliss](https://avatars.githubusercontent.com/u/13621738?v=4)](https://github.com/jackbayliss "jackbayliss (8 commits)")[![sweptsquash](https://avatars.githubusercontent.com/u/9886472?v=4)](https://github.com/sweptsquash "sweptsquash (6 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (4 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (4 commits)")[![riasvdv](https://avatars.githubusercontent.com/u/3626559?v=4)](https://github.com/riasvdv "riasvdv (4 commits)")[![shuvroroy](https://avatars.githubusercontent.com/u/21066418?v=4)](https://github.com/shuvroroy "shuvroroy (2 commits)")[![angeljqv](https://avatars.githubusercontent.com/u/79208641?v=4)](https://github.com/angeljqv "angeljqv (2 commits)")[![thecaliskan](https://avatars.githubusercontent.com/u/13554944?v=4)](https://github.com/thecaliskan "thecaliskan (1 commits)")[![mbardelmeijer](https://avatars.githubusercontent.com/u/1583095?v=4)](https://github.com/mbardelmeijer "mbardelmeijer (1 commits)")[![tadhgboyle](https://avatars.githubusercontent.com/u/26070412?v=4)](https://github.com/tadhgboyle "tadhgboyle (1 commits)")[![1RV34](https://avatars.githubusercontent.com/u/4242602?v=4)](https://github.com/1RV34 "1RV34 (1 commits)")

---

Tags

debuggingphpspatieBacktrace

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/spatie-backtrace/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-backtrace/health.svg)](https://phpackages.com/packages/spatie-backtrace)
```

###  Alternatives

[symfony/stopwatch

Provides a way to profile code

2.8k387.2M918](/packages/symfony-stopwatch)[spatie/ray

Debug with Ray to fix problems faster

62242.5M758](/packages/spatie-ray)[spatie/laravel-web-tinker

Artisan Tinker in your browser

1.2k3.8M6](/packages/spatie-laravel-web-tinker)[spatie/laravel-ray

Easily debug Laravel apps

31738.4M2.8k](/packages/spatie-laravel-ray)[spatie/global-ray

Enable Ray in all PHP files on your system

21863.0k1](/packages/spatie-global-ray)[spatie/laravel-artisan-dd

Run dd from your commandline

16387.7k1](/packages/spatie-laravel-artisan-dd)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
