Giter Club home page Giter Club logo

larastan's Introduction

Larastan Logo

Larastan Example

Build Status Total Downloads Latest Version License


⚗️ About Larastan

If you are using a Laravel version older than 9.x, please refer to Larastan v1.x with PHPStan 1.8.x.

Larastan was created by Can Vural and Nuno Maduro, got artwork designed by @Caneco, is maintained by Can Vural, Nuno Maduro, and Viktor Szépe, and is a PHPStan wrapper for Laravel. Larastan focuses on finding errors in your code. It catches whole classes of bugs even before you write tests for the code.

  • Adds static typing to Laravel to improve developer productivity and code quality
  • Supports most of Laravel's beautiful magic
  • Discovers bugs in your code

While by definition, "static analysis" doesn't load any of your application's code. Larastan boots your application's container, so it can resolve types that are only possible to compute at runtime. That's why we use the term "code analysis" instead of "static analysis".

✨ Getting Started In 3 Steps

Requires:

1: First, you may use Composer to install Larastan as a development dependency into your Laravel project:

composer require larastan/larastan:^2.0 --dev

Using Larastan for analysing Laravel packages? You may need to install orchestra/testbench.

2: Then, create a phpstan.neon or phpstan.neon.dist file in the root of your application. It might look like this:

includes:
    - vendor/larastan/larastan/extension.neon

parameters:

    paths:
        - app/

    # Level 9 is the highest level
    level: 5

#    ignoreErrors:
#        - '#PHPDoc tag @var#'
#
#    excludePaths:
#        - ./*/*/FileToBeExcluded.php
#
#    checkMissingIterableValueType: false

For all available options, please take a look at the PHPStan documentation: https://phpstan.org/config-reference

3: Finally, you may start analyzing your code using the phpstan console command:

./vendor/bin/phpstan analyse

If you are getting the error Allowed memory size exhausted, then you can use the --memory-limit option fix the problem:

./vendor/bin/phpstan analyse --memory-limit=2G

Ignoring errors

Ignoring a specific error can be done either with a php comment or in the configuration file:

// @phpstan-ignore-next-line
$test->badMethod();

$test->badMethod(); // @phpstan-ignore-line

When ignoring errors in PHPStan's configuration file, they are ignored by writing a regex based on error messages:

parameters:
    ignoreErrors:
        - '#Call to an undefined method .*badMethod\(\)#'

Baseline file

In older codebases it might be hard to spend the time fixing all the code to pass a high PHPStan Level.

To get around this a baseline file can be generated. The baseline file will create a configuration file with all of the current errors, so new code can be written following a higher standard than the old code. (PHPStan Docs)

./vendor/bin/phpstan analyse --generate-baseline

Rules

A list of configurable rules specific to Laravel can be found here.

Features

A list of Larastan features can be found here.

Custom PHPDoc types

A list of PHPDoc types specific to Larastan can be found here.

Custom PHPStan config parameters

A list of custom config parameters that you can use in your PHPStan config file can be found here.

Errors To Ignore

Some parts of Laravel are currently too magical for Larastan/PHPStan to understand. We listed common errors to ignore, add them as needed

👊🏻 Contributing

Thank you for considering contributing to Larastan. All the contribution guidelines are mentioned here.

📖 License

Larastan is an open-sourced software licensed under the MIT license.

larastan's People

Contributors

0xb4lint avatar bastien-phi avatar bertvanhoekelen avatar calebdw avatar canvural avatar crissi avatar crynobone avatar cyberiaresurrection avatar daanra avatar deleugpn avatar erikgaal avatar grahamcampbell avatar haringsrob avatar j3j5 avatar johanvanhelden avatar josh-g avatar kylekatarnls avatar mad-briller avatar mr-feek avatar mvdnbrk avatar nunomaduro avatar ondrejmirtes avatar prinsfrank avatar rajyan avatar sebdesign avatar spawnia avatar stylecibot avatar szepeviktor avatar tpetry avatar uksusoff avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

larastan's Issues

Does not work on Windows

'.' is not recognized as an internal or external command, operable program or batch file.

Looks like it's to do with Console\CodeAnalyseCommand line 42.

Wrong "always false" checks

I've got a simple class, this is a snippet from it:

/** @var \App\Domain\User\Models\User */
protected $user;

public function __construct(User $user = null)
{
    $this->user = $user;
}

Calling this in another function, in that same class, results in an error:

if (! $this->user) {
    return [];
}
Negated boolean is always false.

Another error occurs, which seems to have to same cause:

return is_null($this->user);
Call to function is_null() with App\Domain\User\Models\User will always evaluate to false.

Using Eloquent whereParam()

Throws an error Call to an undefined static method *whereParamId* when you do App\Model::whereParamId($id)->get(). It wants you to do App\Model::where('param_id', $id)->get().

Call to an undefined method route()/back().

return redirect()->route('index');

Produce:

Call to an undefined method Illuminate\Http\RedirectResponse|Illuminate\Routing\Redirector::route()


return redirect()->back();

Produce:

Call to an undefined method Illuminate\Http\RedirectResponse|Illuminate\Routing\Redirector::back().

Container errors in controllers with validation rules.

Almost all my controllers generate errors, saying they try to resolve an undefined class:

  Line   app/Http/Admin/Controllers/Settings/UnitAssignmentOrderController.php
 ------ -----------------------------------------------------------------------
         Internal error: Class unit_types does not exist
         Run PHPStan with --debug option and post the stack trace to:
         https://github.com/phpstan/phpstan/issues/new
  Line   app/Http/Admin/Controllers/Settings/UnitPricesController.php
 ------ --------------------------------------------------------------
         Internal error: Class message does not exist
         Run PHPStan with --debug option and post the stack trace to:
         https://github.com/phpstan/phpstan/issues/new
  Line   app/Http/Admin/Controllers/Settings/InvoiceLabelsController.php
 ------ -----------------------------------------------------------------
         Internal error: Class labels does not exist
         Run PHPStan with --debug option and post the stack trace to:
         https://github.com/phpstan/phpstan/issues/new

etc.

Running with --debug shows this:

 ReflectionException  : Class labels does not exist

  at /vendor/laravel/framework/src/Illuminate/Container/Container.php: 767
  763:         if ($concrete instanceof Closure) {
  764:             return $concrete($this, $this->getLastParameterOverride());
  765:         }
  766:
  767:         $reflector = new ReflectionClass($concrete);
  768:
  769:         // If the type is not instantiable, the developer is attempting to resolve
  770:         // an abstract type such as an Interface of Abstract Class and there is
  771:         // no binding registered for the abstractions so we need to bail out.
  772:         if (! $reflector->isInstantiable()) {

  Exception trace:

  1   ReflectionClass::__construct("labels")
      /vendor/laravel/framework/src/Illuminate/Container/Container.php : 767

  2   Illuminate\Container\Container::build("labels")
      /vendor/laravel/framework/src/Illuminate/Container/Container.php : 646

I'm not 100% sure where this error comes from. It seems to have something to do with request validation:

$validated = collect($request->validate($this->rules()));

// ...

protected function rules(): array
{
    return [
        'labels' => 'array',
        // ...
    ];
}

All these fields seem to be the first entry in the validation rules, probably it has something to do with the ->validate macro on Illuminate\Http\Request ?

Error while installing

I'm getting this error after running:
composer require --dev nunomaduro/larastan

screen shot 2018-07-18 at 2 49 45 pm

My require section in composer.json is:

"require": {
        "php": ">=7.1.3",
        "arcanedev/log-viewer": "^4.5",
        "bensampo/laravel-enum": "^1.4",
        "browner12/helpers": "^2.1",
        "darkaonline/l5-swagger": "5.6.*",
        "doctrine/dbal": "^2.7",
        "fideloper/proxy": "~4.0",
        "gladcodes/keygen": "^1.1",
        "jrm2k6/cloudder": "0.4.*",
        "laravel/framework": "5.6.*",
        "laravel/passport": "^5.0",
        "laravel/tinker": "~1.0",
        "sentry/sentry-laravel": "^0.9.0",
        "simshaun/recurr": "^3.0",
        "zircote/swagger-php": "3.*",
    },

Any ideas how to fix this?

Memory limit issue reached

Hey guys, super excited to try out the package.

Looks like I'm getting a memory exhausted error when running the following:

php artisan code:analyse --debug

/Users/luke/code/project/app/Mail/Frontend/Contact/SendContact.php
/Users/luke/code/project/app/Mail/Frontend/Quote/SendCreateQuote.php
/Users/luke/code/project/app/Mail/Frontend/Quote/SendCreateAdminQuote.php
/Users/luke/code/project/app/Mail/Frontend/Quote/SendEstimatorOnTheWay.php
/Users/luke/code/project/app/Mail/Frontend/Quote/SendUpdateQuote.php
/Users/luke/code/project/app/Mail/Frontend/Quote/SendQuoteReminderEmail.php
/Users/luke/code/project/app/Mail/Frontend/Quote/SendAcceptQuote.php
/Users/luke/code/project/app/Mail/Frontend/Job/SendSubJobAssign.php
/Users/luke/code/project/app/Mail/Frontend/Job/SendSubJobStartDayReminder.php
/Users/luke/code/project/app/Mail/Frontend/Report/SendCreateReport.php
/Users/luke/code/project/app/Mail/Frontend/Invoice/SendUpdateStatusInvoice.php
/Users/luke/code/project/app/Mail/Advance/SendUpdateStatusAdvance.php
/Users/luke/code/project/app/Providers/AppServiceProvider.php
/Users/luke/code/project/app/Providers/AuthServiceProvider.php
/Users/luke/code/project/app/Providers/BladeServiceProvider.php
/Users/luke/code/project/app/Providers/RouteServiceProvider.php
PHP Fatal error:  Allowed memory size of 2147483648 bytes exhausted (tried to allocate 20480 bytes) in /Users/luke/code/project/vendor/nunomaduro/larastan/src/Middlewares/Mixins.php on line 97
PHP Fatal error:  Allowed memory size of 2147483648 bytes exhausted (tried to allocate 32768 bytes) in /Users/luke/code/project/vendor/symfony/debug/Exception/FatalErrorException.php on line 1

I also tried upping the memory limit to the same error, the same thing happens when I specify the path too. Is there anything that flags up as something else I can try?

Cheers,

ReturnTypes\ModelExtension::getTypeFromStaticMethodCall() returns a boolean

   Symfony\Component\Debug\Exception\FatalThrowableError  : Return value of NunoMaduro\Larastan\ReturnTypes\ModelExtension::getTypeFromStaticMethodCall() must implement interface PHPStan\Type\Type, boolean returned

  at /home/viktor/src/gallerytool/vendor/nunomaduro/larastan/src/ReturnTypes/ModelExtension.php:115
    111|                 }
    112|             }
    113|         }
    114|
  > 115|         return $returnType;
    116|     }
    117|
    118|     /**
    119|      * Replaces Static Types by the provided Static Type.

  Exception trace:

  1   NunoMaduro\Larastan\ReturnTypes\ModelExtension::getTypeFromStaticMethodCall(Object(Mockery_0_PHPStan_Reflection_Php_PhpMethodReflection_PHPStan_Reflection_Php_PhpMethodReflection), Object(PhpParser\Node\Expr\StaticCall), Object(PHPStan\Analyser\Scope))
      /home/viktor/src/gallerytool/vendor/phpstan/phpstan/src/Analyser/Scope.php:1253

  2   PHPStan\Analyser\Scope::resolveType(Object(PhpParser\Node\Expr\StaticCall))
      /home/viktor/src/gallerytool/vendor/phpstan/phpstan/src/Analyser/Scope.php:352

After debugging it turned out in line 110 $types is empty array.

Undefined property Application::$request.

Access to an undefined property Illuminate\Contracts\Foundation\Application::$request.

This is the calling code, in a service provider.

$this->app->request->getHost()

Absolute paths to configuration etc. files

Please notify users that files must have absolute path.

E.g. -c, --configuration=CONFIGURATION Path to project configuration file could be -c, --configuration=CONFIGURATION Absolute path to project configuration file

Also for autoload-file.

Call to an undefined method withHeaders()

Is it another false positive for Laravel magic (__call())?

response($this->pdf->render($this->request, $model), 200)->withHeaders([ ...  ]);

Call to an undefined method Illuminate\Contracts\Routing\ResponseFactory|Symfony\Component\HttpFoundation\Response::withHeaders().

with --level=2

[Proposal] larastan-gui

As part of this package, or a as a opt-in separate one,

A graphic report executer and log viewer.

  • Route endpoint: /larastan

    • all routes registered in provider if environment !== 'production' or environment === 'local'
  • Assets don't need to be published to public folder

    • route endpoint /_larastan/asset/{asset} and the file will be streamed directly from the vendor folder
  • Layout with input for paths to be analyzed, default: "app", and you can add more

  • Labels / badges for severity levels, warnings

Internal error with maatwebsite/excel:2.1.28

Newest larastan on level 2.

<?php

namespace App\Services;

use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Log;

class Importer
{
    /**
     * Read in a saved excel file
     *
     * @param string $filename
     */

    public static function read(string $filename, int $skip = 0, int $take = 100)
    {
        return Excel::load('storage/app/import/'.$filename)->skipRows($skip)->takeRows($take)->get();
    }
}

Debug reveals

   ReflectionException  : Class Maatwebsite\Excel\Readers\RowCollection does not exist

  at /home/viktor/src/gallerytool/vendor/nunomaduro/larastan/src/Analyser/Scope.php:111
    107|      */
    108|     private function isContainer(Type $type): bool
    109|     {
    110|         foreach ($type->getReferencedClasses() as $referencedClass) {
  > 111|             if ((new ReflectionClass($referencedClass))->implementsInterface(Container::class)) {
    112|                 return true;
    113|             }
    114|         }
    115|

  Exception trace:

  1   ReflectionClass::__construct("Maatwebsite\Excel\Readers\RowCollection")
      /home/viktor/src/gallerytool/vendor/nunomaduro/larastan/src/Analyser/Scope.php:111

  2   NunoMaduro\Larastan\Analyser\Scope::isContainer(Object(PHPStan\Type\UnionType))
      /home/viktor/src/gallerytool/vendor/nunomaduro/larastan/src/Analyser/Scope.php:49

Doesn't run on Laravel Homestead (on Windows)

When running the command php artisan code:analyse in Putty (SSH'ed into Laravel Homestead) I'm returned with this..

vagrant@homestead:~/project$ php artisan code:analyse

dir=$(cd "${0%[/\\]*}" > /dev/null; cd '../phpstan/phpstan/bin' && pwd)

if [ -d /proc/cygdrive ] && [[ $(which php) == $(readlink -n /proc/cygdrive)/* ]]; then
   # We are in Cgywin using Windows php, so the path must be translated
   dir=$(cygpath -m "$dir");
fi

"${dir}/phpstan" "$@"
vagrant@homestead:~/project$ 

Seems related to #7 however I just installed larastan fresh.

Call to an undefined method user()

auth()->user()

No error on

Auth::user()

Call to an undefined method Illuminate\Contracts\Auth\Factory|Illuminate\Contracts\Auth\Guard::user()

I think the code above is also often used in many different projects.

Eloquent Relationship issue with hasOne

/**
 * @return \Illuminate\Database\Eloquent\Relations\HasOne
 */
public function phone()
{
    return $this->hasOne('App\Phone');
}

Gives the following error:

Class Illuminate\Database\Eloquent\Relations\HasOne referenced with incorrect case: Illuminate\Database\Eloquent\Relations\hasOne.

Redis Facade publish, hmget, expire

Call to an undefined static method Illuminate\Support\Facades\Redis::publish().
Call to an undefined static method Illuminate\Support\Facades\Redis::hmget().
Call to an undefined static method Illuminate\Support\Facades\Redis::expire().

Segmentation fault (core dumped)

Getting a Segmentation fault (core dumped) error when running the code:analyse. Just running phpstan analyse app seems to work fine.

With php artisan code:analyse:

vagrant@homestead:~/code$ php artisan code:analyse
  24/410 [▓░░░░░░░░░░░░░░░░░░░░░░░░░░░]   5%Segmentation fault (core dumped)
vagrant@homestead:~/code$ php artisan code:analyse
PHPStan crashed in the previous run probably because of excessive memory consumption.
It consumed around 32 MB of memory.


To avoid this issue, allow to use more memory with the --memory-limit option.
  24/410 [▓░░░░░░░░░░░░░░░░░░░░░░░░░░░]   5%Segmentation fault (core dumped)

With phpstan analyse app:

vagrant@homestead:~/code$ phpstan analyse app
PHPStan crashed in the previous run probably because of excessive memory consumption.
It consumed around 32 MB of memory.


To avoid this issue, allow to use more memory with the --memory-limit option.
 410/410 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

vagrant@homestead:~/code$ phpstan analyse app
 410/410 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

Call to an undefined method forever().

$response->withCookie(cookie()->forever('name', 'value'));

Produce:

Call to an undefined method Illuminate\Cookie\CookieJar|Symfony\Component\HttpFoundation\Cookie::forever().

Environments without TTY (CI)

Currently unable to run in CI (Drone, not tested in other systems) due to TTY being enabled.

   Symfony\Component\Process\Exception\RuntimeException  : TTY mode requires /dev/tty to be read/writable.

  at /drone/src/github.com/xxx/vendor/symfony/process/Process.php:980
    976|             throw new RuntimeException('TTY mode is not supported on Windows platform.');
    977|         }
    978| 
    979|         if ($tty && !self::isTtySupported()) {
  > 980|             throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');
    981|         }
    982| 
    983|         $this->tty = (bool) $tty;
    984|

  Exception trace:

  1   Symfony\Component\Process\Process::setTty()
      /drone/src/github.com/xxx/vendor/nunomaduro/laravel-code-analyse/src/Console/CodeAnalyseCommand.php:51

  2   NunoMaduro\LaravelCodeAnalyse\Console\CodeAnalyseCommand::handle()
      /drone/src/github.com/xxx/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:29

  Please use the argument -v to see more details.

Support for 5.4

This package looks really awesome!!

Will there ever be support for Laravel 5.4 or 5.5?

Macros: $this variable is a instance of the macroable class or bound closures

When registering a macro, the property is not on the file's class, but it resolves an error like it's supposed to be.

The error:

The error on report:
Line   app/Providers/DuskBrowserServiceProvider.php                                        
------ ------------------------------------------------------------------------------------ 
 18     Access to an undefined property App\Providers\DuskBrowserServiceProvider::$driver.  

The file:

<?php


namespace App\Providers;

use Laravel\Dusk\Browser;
use Illuminate\Support\ServiceProvider;

class DuskBrowserServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        Browser::macro('switchFrame', function($frame) {
            $this->driver->switchTo()->defaultContent()->switchTo()->frame($frame);
            return $this;
        });
    }

    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Call to an undefined scope

Not sure if this is fixable.

The error is this

Call to an undefined method Illuminate\Database\Eloquent\Builder::whereResidence()

The calling code is this

InvoiceLabel::query()
    ->whereResidence($this->residence)
    ->whereId($parameters['id'])
    ->firstOrFail();

The ::query() part returns Illuminate\Database\Eloquent\Builder per its doc blocks, but actually returns the concrete model.

Xampp on Windows

With the latest update, Larastan finally works in Homestead. Unfortunately, it doesn't work anymore with Xampp on Windows. The result, what I get is.

'phpstan' is not recognized as an internal or external command,
operable program or batch file.

Static method Builder::dynamicWhere() invoked with 0 parameters, 1 required.

I've got this piece of code

Module::whereRoot()->get()

whereRoot is a custom scope on Module:

public function scopeWhereRoot(Builder $builder): Builder
{
    return $builder->whereNull('parent_id');
}

The error I get is

Static method Illuminate\Database\Query\Builder::dynamicWhere() invoked with 0 parameters, 1 required.

Resource Response make() method

Parameter #1 ...$parameters of static method
Illuminate\Http\Resources\Json\JsonResource::make() expects
Illuminate\Http\Resources\Json\dynamic, App\UserResource given.

Call to an undefined method with()

return view('user.profile')->with('user', $user);

Produce:

Call to an undefined method Illuminate\Contracts\View\Factory|Illuminate\View\View::with().

php artisan code:analyse --level=max

When I want to run this command, I get as result
Path D:\xxx\D:\xxx\app does not exist

When php artisan code:analyse --paths="app" or php artisan code:analyse --paths="app" --level=max runs then Larastan knows, where the app folder is.

Call to an undefined method json()

Hello!

Has it been reported already?

Call to an undefined method Illuminate\Contracts\View\Factory|Illuminate\View\View::json().

class ArtistsController extends Controller
{

    /**
     * Duplicate the specified resource.
     *
     * @param  \App\Models\Artist  $artist
     * @return void
     */
    public function duplicate(Artist $artist)
    {
        $model = $artist->replicate();

        $model->push();

        return view()->json($model);
    }

60 second timeout is a bit to strict for our codebase

I know this is not a finished product but wanted to bring this under your attention. A 60 second timeout is a bit too strict for our application it looks like.

   Symfony\Component\Process\Exception\ProcessTimedOutException  : The process "./phpstan analyse --level=max --autoload-file=/private/var/www/xxx/vendor/autoload.php --configuration=/private/var/www/xxx/vendor/weebly/phpstan-laravel/extension.neon /private/var/www/xxx/app" exceeded the timeout of 60 seconds.

  at /private/var/www/xxx/vendor/symfony/process/Process.php:1154
    1150| 
    1151|         if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
    1152|             $this->stop(0);
    1153| 
  > 1154|             throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
    1155|         }
    1156| 
    1157|         if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
    1158|             $this->stop(0);

  Exception trace:

  1   Symfony\Component\Process\Process::checkTimeout()
      /private/var/www/xxx/vendor/symfony/process/Process.php:573

  2   Symfony\Component\Process\Process::getIterator()
      /private/var/www/xxx/vendor/nunomaduro/laravel-code-analyse/src/Console/CodeAnalyseCommand.php:54

  Please use the argument -v to see more details.

Possibly a $process->setTimeout(null); should be enough 😄

Weird style

The commands running always to the end, but afterwards the style of the list/table is a bit weird. It runs in full screen. But sometimes it does happen that you have the 100% at the end of the list/table and the content of errors is between the penultimate line and the third penultimate line with the amount of tasks. Sometimes I also had it that the last line was between the second and third part of the list of erros.

   0/133 [>---------------------------]   0%

  13/133 [==>-------------------------]   9%

  26/133 [=====>----------------------]  19%

  39/133 [========>-------------------]  29%

  52/133 [==========>-----------------]  39%

  65/133 [=============>--------------]  48%

  78/133 [================>-----------]  58%

  91/133 [===================>--------]  68%

 104/133 [=====================>------]  78%

 117/133 [========================>---]  87%


 ------ ---------------------------------------------------------------------------------------------------------------------------------------
  Line   app\Exceptions\Handler.php
 ------ ---------------------------------------------------------------------------------------------------------------------------------------
  51     Method App\Exceptions\Handler::render() should return Illuminate\Http\Response but returns Symfony\Component\HttpFoundation\Response.
 ------ ---------------------------------------------------------------------------------------------------------------------------------------

 130/133 [===========================>]  97%
 133/133 [============================] 100%

Memory limit reached when trying to count Eloquent models.

When trying to count an Eloquent model using the query builder, I receive a memory limit error:

<?php

namespace App;

use App\User;

class Test
{
    public function foo()
    {
        // Any of these combinations results in a memory limit error
        User::where('name', 'bar')->count();
        User::whereName('bar')->count();
        User::count();

        // It also has nothing to do with facades
        $user = new User();
        $user->count();
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.