Explore all Laravel open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Laravel

Faker

laravel-debugbar

Skip mail on Laravel 9

laravel-ide-helper

voyager

Release v1.5.2

laravel-admin

Popular Libraries in Laravel

Faker

by fzaninotto doticonphpdoticon

star image 26055 doticonNOASSERTION

Faker is a PHP library that generates fake data for you

laravel-debugbar

by barryvdh doticonphpdoticon

star image 13667 doticonMIT

Laravel Debugbar (Integrates PHP Debug Bar)

laravel-ide-helper

by barryvdh doticonphpdoticon

star image 12086 doticonMIT

Laravel IDE Helper

voyager

by the-control-group doticonphpdoticon

star image 10951 doticonMIT

Voyager - The Missing Laravel Admin

laravel-admin

by z-song doticonphpdoticon

star image 10284 doticonMIT

Build a full-featured administrative interface in ten minutes

lang

by Laravel-Lang doticonphpdoticon

star image 6575 doticonMIT

List of 78 languages for Laravel Framework, Laravel Jetstream, Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova, Laravel Spark and Laravel UI.

entrust

by Zizaco doticonphpdoticon

star image 6180 doticonMIT

Role-based Permissions for Laravel 5

laravel-cors

by fruitcake doticonphpdoticon

star image 6005 doticonMIT

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application

laravel-mongodb

by jenssegers doticonphpdoticon

star image 5966 doticonMIT

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Trending New libraries in Laravel

jetstream

by laravel doticonphpdoticon

star image 3281 doticonMIT

Tailwind scaffolding for the Laravel framework.

breeze

by laravel doticonphpdoticon

star image 1728 doticonMIT

Minimal Laravel authentication scaffolding with Blade and Tailwind.

fortify

by laravel doticonphpdoticon

star image 1283 doticonMIT

Backend controllers and scaffolding for Laravel authentication.

laravel-livewire-tables

by rappasoft doticonphpdoticon

star image 982 doticonMIT

A dynamic table component for Laravel Livewire - For Slack access, visit:

laravel-migrations-generator

by kitloong doticonphpdoticon

star image 924 doticonMIT

Laravel Migrations Generator: Automatically generate your migrations from an existing database schema.

laravel-cross-eloquent-search

by protonemedia doticonphpdoticon

star image 716 doticonMIT

Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single or multiple columns.

tall-forms

by tanthammar doticonphpdoticon

star image 565 doticonMIT

Laravel Livewire (TALL-stack) form generator with realtime validation, file uploads, array fields, blade form input components and more.

enlighten

by StydeNet doticonphpdoticon

star image 563 doticonMIT

Enlighten your APIs with auto-generated documentation

laravel-schedule-monitor

by spatie doticonphpdoticon

star image 542 doticonMIT

Monitor scheduled tasks in a Laravel app

Top Authors in Laravel

1

spatie

36 Libraries

star icon15356

2

laravel-enso

33 Libraries

star icon473

3

laravel-notification-channels

27 Libraries

star icon1278

4

php-flasher

19 Libraries

star icon164

5

laravel-admin-extensions

19 Libraries

star icon771

6

ARCANEDEV

18 Libraries

star icon452

7

appstract

18 Libraries

star icon3637

8

overtrue

15 Libraries

star icon3616

9

laravel

13 Libraries

star icon14743

10

laravel-shift

13 Libraries

star icon118

1

36 Libraries

star icon15356

2

33 Libraries

star icon473

4

19 Libraries

star icon164

5

19 Libraries

star icon771

6

18 Libraries

star icon452

7

18 Libraries

star icon3637

8

15 Libraries

star icon3616

9

13 Libraries

star icon14743

10

13 Libraries

star icon118

Trending Kits in Laravel

No Trending Kits are available at this moment for Laravel

Trending Discussions on Laravel

Call to undefined method App\Models\Category::factory() laravel

Error: While updating laravel 8 to 9. Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead

Error: Cannot find module 'webpack/lib/rules/DescriptionDataMatcherRulePlugin' Require stack:

enum class in ternary expression

How to allow to use the master password in Laravel 8 by overriding Auth structure?

Laravel eloquent with multiple inner joins

PHP Serial connection read timeout

Laravel 8 ConsoleTvs 7 - Apply dataset configuration through extra argument of advancedDataset method

What is the "Add #[Pure] attribute" inspection in PhpStorm checking for?

QUESTION

Call to undefined method App\Models\Category::factory() laravel

Asked 2022-Mar-31 at 13:28

I have the error stated above, and here is the copy log

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27

Here is the databaseseeder.php class since the error is there:

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76

There is the error line:

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76\App\Models\Category::factory()->count($cantidadUsuarios)->create();
77

Here we got the category class:

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76\App\Models\Category::factory()->count($cantidadUsuarios)->create();
77<?php
78
79namespace App\Models;
80
81use Illuminate\Database\Eloquent\Factories\HasFactory;
82use Illuminate\Database\Eloquent\Model;
83
84class Category extends Model
85{
86    public $table = "categories";
87
88    protected $fillable = [
89        'name',
90        'description',
91    ];
92}
93

Here we got the category factory:

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76\App\Models\Category::factory()->count($cantidadUsuarios)->create();
77<?php
78
79namespace App\Models;
80
81use Illuminate\Database\Eloquent\Factories\HasFactory;
82use Illuminate\Database\Eloquent\Model;
83
84class Category extends Model
85{
86    public $table = "categories";
87
88    protected $fillable = [
89        'name',
90        'description',
91    ];
92}
93<?php
94
95namespace Database\Factories;
96
97use App\Models\Category;
98use Illuminate\Database\Eloquent\Factories\Factory;
99
100class CategoryFactory extends Factory
101{
102    /**
103     * The name of the factory's corresponding model.
104     *
105     * @var string
106     */
107    protected $model = Category::class;
108
109    /**
110     * Define the model's default state.
111     *
112     * @return array
113     */
114    public function definition()
115    {
116        return [
117            //
118             'name' => $this->faker->word,
119            'description' => $this->faker->paragraph(1),
120        ];
121    }
122}
123

Here is the category migration:

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76\App\Models\Category::factory()->count($cantidadUsuarios)->create();
77<?php
78
79namespace App\Models;
80
81use Illuminate\Database\Eloquent\Factories\HasFactory;
82use Illuminate\Database\Eloquent\Model;
83
84class Category extends Model
85{
86    public $table = "categories";
87
88    protected $fillable = [
89        'name',
90        'description',
91    ];
92}
93<?php
94
95namespace Database\Factories;
96
97use App\Models\Category;
98use Illuminate\Database\Eloquent\Factories\Factory;
99
100class CategoryFactory extends Factory
101{
102    /**
103     * The name of the factory's corresponding model.
104     *
105     * @var string
106     */
107    protected $model = Category::class;
108
109    /**
110     * Define the model's default state.
111     *
112     * @return array
113     */
114    public function definition()
115    {
116        return [
117            //
118             'name' => $this->faker->word,
119            'description' => $this->faker->paragraph(1),
120        ];
121    }
122}
123<?php
124
125use App\Models\Product;
126use Illuminate\Database\Migrations\Migration;
127use Illuminate\Database\Schema\Blueprint;
128use Illuminate\Support\Facades\Schema;
129
130class CreateCategoriesTable extends Migration
131{
132    /**
133     * Run the migrations.
134     *
135     * @return void
136     */
137    public function up()
138    {
139        Schema::create('categories', function (Blueprint $table) {
140            $table->increments('id');
141            $table->string('name');
142            $table->string('description', 1000);
143            $table->integer('quantity')->unsigned();
144            $table->string('status')->default(Product::PRODUCTO_NO_DISPONIBLE);
145            $table->string('image');
146            $table->integer('seller_id')->unsigned();
147            $table->timestamps();
148
149            $table->foreign('seller_id')->references('id')->on('users');
150        });
151    }
152
153    /**
154     * Reverse the migrations.
155     *
156     * @return void
157     */
158    public function down()
159    {
160        Schema::dropIfExists('categories');
161    }
162}
163

I am posting all you need since I am new to this and I cannot find the problem.

ANSWER

Answered 2021-Aug-01 at 00:51

You need to use the factory trait for the model to have the factory() method available.

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76\App\Models\Category::factory()->count($cantidadUsuarios)->create();
77<?php
78
79namespace App\Models;
80
81use Illuminate\Database\Eloquent\Factories\HasFactory;
82use Illuminate\Database\Eloquent\Model;
83
84class Category extends Model
85{
86    public $table = "categories";
87
88    protected $fillable = [
89        'name',
90        'description',
91    ];
92}
93<?php
94
95namespace Database\Factories;
96
97use App\Models\Category;
98use Illuminate\Database\Eloquent\Factories\Factory;
99
100class CategoryFactory extends Factory
101{
102    /**
103     * The name of the factory's corresponding model.
104     *
105     * @var string
106     */
107    protected $model = Category::class;
108
109    /**
110     * Define the model's default state.
111     *
112     * @return array
113     */
114    public function definition()
115    {
116        return [
117            //
118             'name' => $this->faker->word,
119            'description' => $this->faker->paragraph(1),
120        ];
121    }
122}
123<?php
124
125use App\Models\Product;
126use Illuminate\Database\Migrations\Migration;
127use Illuminate\Database\Schema\Blueprint;
128use Illuminate\Support\Facades\Schema;
129
130class CreateCategoriesTable extends Migration
131{
132    /**
133     * Run the migrations.
134     *
135     * @return void
136     */
137    public function up()
138    {
139        Schema::create('categories', function (Blueprint $table) {
140            $table->increments('id');
141            $table->string('name');
142            $table->string('description', 1000);
143            $table->integer('quantity')->unsigned();
144            $table->string('status')->default(Product::PRODUCTO_NO_DISPONIBLE);
145            $table->string('image');
146            $table->integer('seller_id')->unsigned();
147            $table->timestamps();
148
149            $table->foreign('seller_id')->references('id')->on('users');
150        });
151    }
152
153    /**
154     * Reverse the migrations.
155     *
156     * @return void
157     */
158    public function down()
159    {
160        Schema::dropIfExists('categories');
161    }
162}
163class Category extends Model
164{
165   use HasFactory;
166
167   ...
168}
169

Source https://stackoverflow.com/questions/68606726

QUESTION

Error: While updating laravel 8 to 9. Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Asked 2022-Mar-29 at 06:51

Nothing to install, update or remove Generating optimized autoload files Class App\Helpers\Helper located in C:/wamp64/www/vuexylaravel/app\Helpers\helpers.php does not comply with psr-4 autoloading standard. Skipping. > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi

1   Error 
2
3  Undefined constant Illuminate\Http\Request::HEADER_X_FORWARDED_ALL
4  at C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php:48
5     44▕      * - 'HEADER_X_FORWARDED_AWS_ELB' (If you are using AWS Elastic Load Balancer)
6     45▕      *
7     46▕      * @link https://symfony.com/doc/current/deployment/proxies.html
8     47▕      */
9  ➜  48▕     'headers' => Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,
10     49▕
11     50▕ ];
12     51▕
13
14  1   C:\wamp64\www\vuexylaravel\vendor\laravel\framework\src\Illuminate\Support\ServiceProvider.php:138
15      require()
16
17  2   C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\src\TrustedProxyServiceProvider.php:28
18      Illuminate\Support\ServiceProvider::mergeConfigFrom("C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php", "trustedproxy")
19Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
20

ANSWER

Answered 2022-Feb-13 at 17:35

If you are upgrading your Laravel 8 project to Laravel 9 by importing your existing application code into a totally new Laravel 9 application skeleton, you may need to update your application's "trusted proxy" middleware.

Within your app/Http/Middleware/TrustProxies.php file, update use Fideloper\Proxy\TrustProxies as Middleware to use Illuminate\Http\Middleware\TrustProxies as Middleware.

Next, within app/Http/Middleware/TrustProxies.php, you should update the $headers property definition:

// Before...

protected $headers = Request::HEADER_X_FORWARDED_ALL;

// After...

1   Error 
2
3  Undefined constant Illuminate\Http\Request::HEADER_X_FORWARDED_ALL
4  at C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php:48
5     44▕      * - 'HEADER_X_FORWARDED_AWS_ELB' (If you are using AWS Elastic Load Balancer)
6     45▕      *
7     46▕      * @link https://symfony.com/doc/current/deployment/proxies.html
8     47▕      */
9  ➜  48▕     'headers' => Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,
10     49▕
11     50▕ ];
12     51▕
13
14  1   C:\wamp64\www\vuexylaravel\vendor\laravel\framework\src\Illuminate\Support\ServiceProvider.php:138
15      require()
16
17  2   C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\src\TrustedProxyServiceProvider.php:28
18      Illuminate\Support\ServiceProvider::mergeConfigFrom("C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php", "trustedproxy")
19Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
20protected $headers =
21    Request::HEADER_X_FORWARDED_FOR |
22    Request::HEADER_X_FORWARDED_HOST |
23    Request::HEADER_X_FORWARDED_PORT |
24    Request::HEADER_X_FORWARDED_PROTO |
25    Request::HEADER_X_FORWARDED_AWS_ELB;
26

then run composer update

Make sure you are using PHP 8.0

Source https://stackoverflow.com/questions/71103241

QUESTION

Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead

Asked 2022-Feb-28 at 12:11

I can't install breez and npm for this situation. What should I do to solve this problem? When I'm going to create a laravel project show this and breez install time too.

Console screen

ANSWER

Answered 2022-Jan-06 at 16:33

$ composer require “swiftmailer/swiftmailer:^6.0” Here is the simplest way to send emails with Swift Mailer:

1require_once ‘/path/to/vendor/autoload.php’;
2

// Create the Transport

1require_once ‘/path/to/vendor/autoload.php’;
2$transport = (new Swift_SmtpTransport(‘smtp.example.org’, 25))
3->setUsername(‘your username’)
4->setPassword(‘your password’)
5;
6

// Create the Mailer using your created Transport $mailer = new Swift_Mailer($transport);

// Create a message

1require_once ‘/path/to/vendor/autoload.php’;
2$transport = (new Swift_SmtpTransport(‘smtp.example.org’, 25))
3->setUsername(‘your username’)
4->setPassword(‘your password’)
5;
6$message = (new Swift_Message(‘Wonderful Subject’))
7->setFrom([‘john@doe.com’ => ‘John Doe’])
8->setTo([‘receiver@domain.org’, ‘other@domain.org’ => ‘A name’])
9->setBody(‘Here is the message itself’)
10;
11

// Send the message

1require_once ‘/path/to/vendor/autoload.php’;
2$transport = (new Swift_SmtpTransport(‘smtp.example.org’, 25))
3->setUsername(‘your username’)
4->setPassword(‘your password’)
5;
6$message = (new Swift_Message(‘Wonderful Subject’))
7->setFrom([‘john@doe.com’ => ‘John Doe’])
8->setTo([‘receiver@domain.org’, ‘other@domain.org’ => ‘A name’])
9->setBody(‘Here is the message itself’)
10;
11$result = $mailer->send($message);
12

You can also use Sendmail as a transport:

// Sendmail

1require_once ‘/path/to/vendor/autoload.php’;
2$transport = (new Swift_SmtpTransport(‘smtp.example.org’, 25))
3->setUsername(‘your username’)
4->setPassword(‘your password’)
5;
6$message = (new Swift_Message(‘Wonderful Subject’))
7->setFrom([‘john@doe.com’ => ‘John Doe’])
8->setTo([‘receiver@domain.org’, ‘other@domain.org’ => ‘A name’])
9->setBody(‘Here is the message itself’)
10;
11$result = $mailer->send($message);
12$transport = new Swift_SendmailTransport(‘/usr/sbin/sendmail -bs’);
13

Source https://stackoverflow.com/questions/70105920

QUESTION

Error: Cannot find module 'webpack/lib/rules/DescriptionDataMatcherRulePlugin' Require stack:

Asked 2022-Feb-26 at 09:58

I have webpack-cli installed on my laravel project. I don't know why first of all we need it to run my vue app but this is causing an error:

When I run npm run dev or npm run hot

1[webpack-cli] Error: Cannot find module 'webpack/lib/rules/DescriptionDataMatcherRulePlugin'
2Require stack:
3- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\plugin-webpack5.js
4- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\plugin.js
5- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\index.js
6- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\src\components\Vue.js
7- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\src\components\ComponentRegistrar.js
8- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\src\Mix.js
9- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\setup\webpack.config.js
10- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack-cli\lib\webpack-cli.js
11- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack-cli\lib\bootstrap.js
12- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack-cli\bin\cli.js
13- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack\bin\webpack.js
14    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
15    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
16    at Module.require (internal/modules/cjs/loader.js:974:19)
17    at require (internal/modules/cjs/helpers.js:93:18)
18    at Object.<anonymous> (C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\plugin-webpack5.js:6:42)
19    at Module._compile (internal/modules/cjs/loader.js:1085:14)
20    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
21    at Module.load (internal/modules/cjs/loader.js:950:32)
22    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
23    at Module.require (internal/modules/cjs/loader.js:974:19) {
24  code: 'MODULE_NOT_FOUND',
25  requireStack: [
26    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\vue-loader\\lib\\plugin-webpack5.js',
27    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\vue-loader\\lib\\plugin.js',
28    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\vue-loader\\lib\\index.js',
29    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\src\\components\\Vue.js',
30    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\src\\components\\ComponentRegistrar.js',
31    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\src\\Mix.js',
32    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\setup\\webpack.config.js',
33    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack-cli\\lib\\webpack-cli.js',
34    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack-cli\\lib\\bootstrap.js',
35    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack-cli\\bin\\cli.js',
36    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack\\bin\\webpack.js'
37  ]
38}
39

Vue is installed also vue-loader, can't understand why it can't find those files. Also, I looked at the node_modules everything is in there ...

ANSWER

Answered 2021-Dec-20 at 09:04

You need to update your vue-loader

1[webpack-cli] Error: Cannot find module 'webpack/lib/rules/DescriptionDataMatcherRulePlugin'
2Require stack:
3- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\plugin-webpack5.js
4- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\plugin.js
5- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\index.js
6- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\src\components\Vue.js
7- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\src\components\ComponentRegistrar.js
8- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\src\Mix.js
9- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\setup\webpack.config.js
10- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack-cli\lib\webpack-cli.js
11- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack-cli\lib\bootstrap.js
12- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack-cli\bin\cli.js
13- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack\bin\webpack.js
14    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
15    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
16    at Module.require (internal/modules/cjs/loader.js:974:19)
17    at require (internal/modules/cjs/helpers.js:93:18)
18    at Object.<anonymous> (C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\plugin-webpack5.js:6:42)
19    at Module._compile (internal/modules/cjs/loader.js:1085:14)
20    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
21    at Module.load (internal/modules/cjs/loader.js:950:32)
22    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
23    at Module.require (internal/modules/cjs/loader.js:974:19) {
24  code: 'MODULE_NOT_FOUND',
25  requireStack: [
26    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\vue-loader\\lib\\plugin-webpack5.js',
27    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\vue-loader\\lib\\plugin.js',
28    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\vue-loader\\lib\\index.js',
29    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\src\\components\\Vue.js',
30    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\src\\components\\ComponentRegistrar.js',
31    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\src\\Mix.js',
32    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\setup\\webpack.config.js',
33    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack-cli\\lib\\webpack-cli.js',
34    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack-cli\\lib\\bootstrap.js',
35    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack-cli\\bin\\cli.js',
36    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack\\bin\\webpack.js'
37  ]
38}
39npm update vue-loader
40

And if it is not installed, install it

1[webpack-cli] Error: Cannot find module 'webpack/lib/rules/DescriptionDataMatcherRulePlugin'
2Require stack:
3- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\plugin-webpack5.js
4- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\plugin.js
5- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\index.js
6- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\src\components\Vue.js
7- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\src\components\ComponentRegistrar.js
8- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\src\Mix.js
9- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\laravel-mix\setup\webpack.config.js
10- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack-cli\lib\webpack-cli.js
11- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack-cli\lib\bootstrap.js
12- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack-cli\bin\cli.js
13- C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\webpack\bin\webpack.js
14    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
15    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
16    at Module.require (internal/modules/cjs/loader.js:974:19)
17    at require (internal/modules/cjs/helpers.js:93:18)
18    at Object.<anonymous> (C:\Users\Viruss\Desktop\test-meme-library\meme-library\node_modules\vue-loader\lib\plugin-webpack5.js:6:42)
19    at Module._compile (internal/modules/cjs/loader.js:1085:14)
20    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
21    at Module.load (internal/modules/cjs/loader.js:950:32)
22    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
23    at Module.require (internal/modules/cjs/loader.js:974:19) {
24  code: 'MODULE_NOT_FOUND',
25  requireStack: [
26    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\vue-loader\\lib\\plugin-webpack5.js',
27    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\vue-loader\\lib\\plugin.js',
28    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\vue-loader\\lib\\index.js',
29    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\src\\components\\Vue.js',
30    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\src\\components\\ComponentRegistrar.js',
31    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\src\\Mix.js',
32    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\laravel-mix\\setup\\webpack.config.js',
33    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack-cli\\lib\\webpack-cli.js',
34    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack-cli\\lib\\bootstrap.js',
35    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack-cli\\bin\\cli.js',
36    'C:\\Users\\Viruss\\Desktop\\test-meme-library\\meme-library\\node_modules\\webpack\\bin\\webpack.js'
37  ]
38}
39npm update vue-loader
40npm i vue-loader
41

Source https://stackoverflow.com/questions/69631437

QUESTION

enum class in ternary expression

Asked 2022-Jan-04 at 11:07

Enums were introduced to PHP very recently. I'm trying them out in a laravel project. I've got my enum class here:

1namespace App\Enums;
2
3enum AlertType
4{
5    case SUCCESS;
6    case ERROR;
7}
8

I'm trying to create an alert class that will take the enum in the constructor to set the severity of the alert, which will decide what colour it is rendered as to the user. Here is that class:

1namespace App\Enums;
2
3enum AlertType
4{
5    case SUCCESS;
6    case ERROR;
7}
8<?php
9
10namespace App\View\Components;
11
12use App\Enums\AlertType;
13use Illuminate\View\Component;
14
15class Alert extends Component
16{
17    public string $contextClass;
18
19    public function __construct(public string $message, AlertType $alertType = AlertType::SUCCESS)
20    {
21        $this->setContextClassFromAlertType($alertType);
22    }
23
24    public function setContextClassFromAlertType(AlertType $alertType)
25    {
26        $this->contextClass = ($alertType === AlertType::SUCCESS ? 'success' : 'error');
27    }
28
29    public function getClassListFromType()
30    {
31        return [
32            'border-' . $this->contextClass,
33            'text-' . $this->contextClass
34        ];
35    }
36
37    public function render()
38    {
39        return view('components.alert', [
40            'class' => implode(' ', $this->getClassListFromType())
41        ]);
42    }
43}
44

This alert will be used in a login form which is built using Laravel Livewire and blade components:

1namespace App\Enums;
2
3enum AlertType
4{
5    case SUCCESS;
6    case ERROR;
7}
8<?php
9
10namespace App\View\Components;
11
12use App\Enums\AlertType;
13use Illuminate\View\Component;
14
15class Alert extends Component
16{
17    public string $contextClass;
18
19    public function __construct(public string $message, AlertType $alertType = AlertType::SUCCESS)
20    {
21        $this->setContextClassFromAlertType($alertType);
22    }
23
24    public function setContextClassFromAlertType(AlertType $alertType)
25    {
26        $this->contextClass = ($alertType === AlertType::SUCCESS ? 'success' : 'error');
27    }
28
29    public function getClassListFromType()
30    {
31        return [
32            'border-' . $this->contextClass,
33            'text-' . $this->contextClass
34        ];
35    }
36
37    public function render()
38    {
39        return view('components.alert', [
40            'class' => implode(' ', $this->getClassListFromType())
41        ]);
42    }
43}
44<form class="grid grid-cols-min-auto-1 gap-x-2" id="login" action="/login" method="post">
45    <x-alert :message="$errorMessage"/>
46    @csrf
47    <label for="email" class="mb-2 text-lg text-sans w-min mt-2 font-thin">Email</label>
48    <x-basic-input wire:model="email" placeholder="{{ $emailPlaceholder }}"/>
49    <label for="password" class="mb-2 text-lg text-sans w-min mt-2 font-thin">Password</label>
50    <x-basic-input wire:model="password"/>
51</form>
52
53

When I come to display the login form I am getting the following error:

Cannot instantiate enum App\Enums\AlertType (View: /resources/views/livewire/forms/login.blade.php)

I think there is something wrong with my enum usage in the Alert component, but I'm not sure where. Can anyone point me in the right direction. I've looked at the rfc for enums but I can't see anything obvious that I'm doing wrong

ANSWER

Answered 2021-Dec-29 at 18:38

I was able to reproduce this error; in my case the stack trace led back to the barryvdh/laravel-debugbar package, not sure if this is the same for you. I was able to resolve it by changing the enum to a backed enum.

I'd recommend making this change regardless, as I expect in a lot of cases strings will be easier to work with than enum instances. (Though TBH this looks like trying to use a new feature just because it's there, not because it makes sense.)

1namespace App\Enums;
2
3enum AlertType
4{
5    case SUCCESS;
6    case ERROR;
7}
8<?php
9
10namespace App\View\Components;
11
12use App\Enums\AlertType;
13use Illuminate\View\Component;
14
15class Alert extends Component
16{
17    public string $contextClass;
18
19    public function __construct(public string $message, AlertType $alertType = AlertType::SUCCESS)
20    {
21        $this->setContextClassFromAlertType($alertType);
22    }
23
24    public function setContextClassFromAlertType(AlertType $alertType)
25    {
26        $this->contextClass = ($alertType === AlertType::SUCCESS ? 'success' : 'error');
27    }
28
29    public function getClassListFromType()
30    {
31        return [
32            'border-' . $this->contextClass,
33            'text-' . $this->contextClass
34        ];
35    }
36
37    public function render()
38    {
39        return view('components.alert', [
40            'class' => implode(' ', $this->getClassListFromType())
41        ]);
42    }
43}
44<form class="grid grid-cols-min-auto-1 gap-x-2" id="login" action="/login" method="post">
45    <x-alert :message="$errorMessage"/>
46    @csrf
47    <label for="email" class="mb-2 text-lg text-sans w-min mt-2 font-thin">Email</label>
48    <x-basic-input wire:model="email" placeholder="{{ $emailPlaceholder }}"/>
49    <label for="password" class="mb-2 text-lg text-sans w-min mt-2 font-thin">Password</label>
50    <x-basic-input wire:model="password"/>
51</form>
52
53namespace App\Enums;
54
55enum AlertType: string
56{
57    case SUCCESS = 'success';
58    case ERROR = 'error';
59    case INFO = 'info';
60}
61

In a backed enum, each item has a string representation that can be accessed using the value property, which we do in the constructor:

1namespace App\Enums;
2
3enum AlertType
4{
5    case SUCCESS;
6    case ERROR;
7}
8<?php
9
10namespace App\View\Components;
11
12use App\Enums\AlertType;
13use Illuminate\View\Component;
14
15class Alert extends Component
16{
17    public string $contextClass;
18
19    public function __construct(public string $message, AlertType $alertType = AlertType::SUCCESS)
20    {
21        $this->setContextClassFromAlertType($alertType);
22    }
23
24    public function setContextClassFromAlertType(AlertType $alertType)
25    {
26        $this->contextClass = ($alertType === AlertType::SUCCESS ? 'success' : 'error');
27    }
28
29    public function getClassListFromType()
30    {
31        return [
32            'border-' . $this->contextClass,
33            'text-' . $this->contextClass
34        ];
35    }
36
37    public function render()
38    {
39        return view('components.alert', [
40            'class' => implode(' ', $this->getClassListFromType())
41        ]);
42    }
43}
44<form class="grid grid-cols-min-auto-1 gap-x-2" id="login" action="/login" method="post">
45    <x-alert :message="$errorMessage"/>
46    @csrf
47    <label for="email" class="mb-2 text-lg text-sans w-min mt-2 font-thin">Email</label>
48    <x-basic-input wire:model="email" placeholder="{{ $emailPlaceholder }}"/>
49    <label for="password" class="mb-2 text-lg text-sans w-min mt-2 font-thin">Password</label>
50    <x-basic-input wire:model="password"/>
51</form>
52
53namespace App\Enums;
54
55enum AlertType: string
56{
57    case SUCCESS = 'success';
58    case ERROR = 'error';
59    case INFO = 'info';
60}
61<?php
62
63namespace App\View\Components;
64
65use App\Enums\AlertType;
66use Illuminate\View\Component;
67
68class Alert extends Component
69{
70    public string $contextClass;
71
72    public function __construct(
73        public string $message,
74        AlertType $alertType = AlertType::SUCCESS,
75    )
76    {
77        $this->contextClass = $alertType->value;
78    }
79
80    public function getClassListFromType()
81    {
82        return [
83            'border-' . $this->contextClass,
84            'text-' . $this->contextClass
85        ];
86    }
87
88    public function render()
89    {
90        return view('components.alert', [
91            'class' => implode(' ', $this->getClassListFromType())
92        ]);
93    }
94}
95

You're now able to use the from() or tryFrom() methods which can add flexibility with alert types saved in a variable. For example:

1namespace App\Enums;
2
3enum AlertType
4{
5    case SUCCESS;
6    case ERROR;
7}
8<?php
9
10namespace App\View\Components;
11
12use App\Enums\AlertType;
13use Illuminate\View\Component;
14
15class Alert extends Component
16{
17    public string $contextClass;
18
19    public function __construct(public string $message, AlertType $alertType = AlertType::SUCCESS)
20    {
21        $this->setContextClassFromAlertType($alertType);
22    }
23
24    public function setContextClassFromAlertType(AlertType $alertType)
25    {
26        $this->contextClass = ($alertType === AlertType::SUCCESS ? 'success' : 'error');
27    }
28
29    public function getClassListFromType()
30    {
31        return [
32            'border-' . $this->contextClass,
33            'text-' . $this->contextClass
34        ];
35    }
36
37    public function render()
38    {
39        return view('components.alert', [
40            'class' => implode(' ', $this->getClassListFromType())
41        ]);
42    }
43}
44<form class="grid grid-cols-min-auto-1 gap-x-2" id="login" action="/login" method="post">
45    <x-alert :message="$errorMessage"/>
46    @csrf
47    <label for="email" class="mb-2 text-lg text-sans w-min mt-2 font-thin">Email</label>
48    <x-basic-input wire:model="email" placeholder="{{ $emailPlaceholder }}"/>
49    <label for="password" class="mb-2 text-lg text-sans w-min mt-2 font-thin">Password</label>
50    <x-basic-input wire:model="password"/>
51</form>
52
53namespace App\Enums;
54
55enum AlertType: string
56{
57    case SUCCESS = 'success';
58    case ERROR = 'error';
59    case INFO = 'info';
60}
61<?php
62
63namespace App\View\Components;
64
65use App\Enums\AlertType;
66use Illuminate\View\Component;
67
68class Alert extends Component
69{
70    public string $contextClass;
71
72    public function __construct(
73        public string $message,
74        AlertType $alertType = AlertType::SUCCESS,
75    )
76    {
77        $this->contextClass = $alertType->value;
78    }
79
80    public function getClassListFromType()
81    {
82        return [
83            'border-' . $this->contextClass,
84            'text-' . $this->contextClass
85        ];
86    }
87
88    public function render()
89    {
90        return view('components.alert', [
91            'class' => implode(' ', $this->getClassListFromType())
92        ]);
93    }
94}
95<x-alert :message="$errorMessage" :type="App\Enums\AlertType::from($errorType)"/>
96

Source https://stackoverflow.com/questions/70489814

QUESTION

How to allow to use the master password in Laravel 8 by overriding Auth structure?

Asked 2022-Jan-03 at 05:36

I've got a website written in pure PHP and now I'm learning Laravel, so I'm remaking this website again to learn the framework. I have used built-in Auth Fasade to make authentication. I would like to understand, what's going on inside, so I decided to learn more by customization. Now I try to make a master password, which would allow direct access to every single account (as it was done in the past).

Unfortunately, I can't find any help, how to do that. When I was looking for similar issues I found only workaround solutions like login by admin and then switching to another account or solution for an older version of Laravel etc.

I started studying the Auth structure by myself, but I lost and I can't even find a place where the password is checked. I also found the very expanded solution on GitHub, so I tried following it step by step, but I failed to make my own, shorter implementation of this. In my old website I needed only one row of code for making a master password, but in Laravel is a huge mountain of code with no change for me to climb on it.

As far I was trying for example changing all places with hasher->check part like here:

1protected function validateCurrentPassword($attribute, $value, $parameters)
2{
3    $auth = $this->container->make('auth');
4    $hasher = $this->container->make('hash');
5
6    $guard = $auth->guard(Arr::first($parameters));
7
8    if ($guard->guest()) {
9        return false;
10    }
11
12    return $hasher->check($value, $guard->user()->getAuthPassword());
13}
14

for

1protected function validateCurrentPassword($attribute, $value, $parameters)
2{
3    $auth = $this->container->make('auth');
4    $hasher = $this->container->make('hash');
5
6    $guard = $auth->guard(Arr::first($parameters));
7
8    if ($guard->guest()) {
9        return false;
10    }
11
12    return $hasher->check($value, $guard->user()->getAuthPassword());
13}
14return ($hasher->check($value, $guard->user()->getAuthPassword()) || $hasher->check($value, 'myHashedMasterPasswordString'));
15

in ValidatesAttributes, DatabaseUserProvider, EloquentUserProvider and DatabaseTokenRepository. But it didn't work. I was following also all instances of the getAuthPassword() code looking for more clues.

My other solution was to place somewhere a code like this:

1protected function validateCurrentPassword($attribute, $value, $parameters)
2{
3    $auth = $this->container->make('auth');
4    $hasher = $this->container->make('hash');
5
6    $guard = $auth->guard(Arr::first($parameters));
7
8    if ($guard->guest()) {
9        return false;
10    }
11
12    return $hasher->check($value, $guard->user()->getAuthPassword());
13}
14return ($hasher->check($value, $guard->user()->getAuthPassword()) || $hasher->check($value, 'myHashedMasterPasswordString'));
15if(Hash::check('myHashedMasterPasswordString',$given_password))
16   Auth::login($user);
17

But I can't find a good place for that in middlewares, providers, or controllers.

I already learned some Auth features, for example, I succeed in changing email authentication for using user login, but I can't figure out, how the passwords are working here. Could you help me with the part that I'm missing? I would appreciate it if someone could explain to me which parts of code should I change and why (if it's not so obvious).

I would like to follow code execution line by line, file by file, so maybe I would find a solution by myself, but I feel like I'm jumping everywhere without any idea, how this all is connected with each other.

ANSWER

Answered 2021-Dec-29 at 02:54

Here is a possible solution.

To use a master password, you can use the loginUsingId function

Search the user by username, then check if the password matches the master password, and if so, log in with the user ID that it found

1protected function validateCurrentPassword($attribute, $value, $parameters)
2{
3    $auth = $this->container->make('auth');
4    $hasher = $this->container->make('hash');
5
6    $guard = $auth->guard(Arr::first($parameters));
7
8    if ($guard->guest()) {
9        return false;
10    }
11
12    return $hasher->check($value, $guard->user()->getAuthPassword());
13}
14return ($hasher->check($value, $guard->user()->getAuthPassword()) || $hasher->check($value, 'myHashedMasterPasswordString'));
15if(Hash::check('myHashedMasterPasswordString',$given_password))
16   Auth::login($user);
17public function loginUser($parameters)
18{
19    $myMasterHashPassword = "abcde";
20    $username = $parameters->username;
21    $password = $parameters->password;
22    $user = User::where('username', $username)->first();
23    if (!$user) {
24        return response("Username not found", 404);
25    }
26    if (Hash::check($myMasterHashPassword, $password)) {
27        Auth::loginUsingId($user->id);
28    }
29}
30

Source https://stackoverflow.com/questions/70393649

QUESTION

Laravel eloquent with multiple inner joins

Asked 2021-Dec-30 at 04:11

I currently am doing a raw sql query however this is causing issues with relationships and model boot methods.

Is it possible to do the following SQL query but with laravel eloquent models by relationship? Note all db tables have FK's defined, and relationships either HasOne or HasMany relationships.

1    $timeBreakDown = DB::select(
2        "SELECT
3                Entries.`task_id`,
4                Entries.`opportunity_id`,
5                SUM(Entries.`total_duration`) as 'duration',
6                Class.`class` as 'class',
7                Subclass.`sub_class` as 'subclass'
8            from entries Entries
9                INNER JOIN `tasks` Task
10                    ON task_id = Task.id
11                INNER JOIN `task_class` Class
12                    ON Task.`class_id` = Class.`id`
13                INNER JOIN `task_subclasses` Subclass
14                    ON Task.`subclass_id` = Subclass.`id`
15                WHERE Entries.`opportunity_id` = '".$opportunity->id."'
16                GROUP BY Entries.`task_id`"
17    );
18

Models are

1    $timeBreakDown = DB::select(
2        "SELECT
3                Entries.`task_id`,
4                Entries.`opportunity_id`,
5                SUM(Entries.`total_duration`) as 'duration',
6                Class.`class` as 'class',
7                Subclass.`sub_class` as 'subclass'
8            from entries Entries
9                INNER JOIN `tasks` Task
10                    ON task_id = Task.id
11                INNER JOIN `task_class` Class
12                    ON Task.`class_id` = Class.`id`
13                INNER JOIN `task_subclasses` Subclass
14                    ON Task.`subclass_id` = Subclass.`id`
15                WHERE Entries.`opportunity_id` = '".$opportunity->id."'
16                GROUP BY Entries.`task_id`"
17    );
18Entries
19Tasks
20Class
21Subclass
22

How would I have to structure my models relationships to handle the above sql query?

enter image description here

ANSWER

Answered 2021-Dec-11 at 23:16

Yes, You can do it with Eloquent I'll share an example with you I can't read your Mess Query sorry for this but I will suggest you to do this

1    $timeBreakDown = DB::select(
2        "SELECT
3                Entries.`task_id`,
4                Entries.`opportunity_id`,
5                SUM(Entries.`total_duration`) as 'duration',
6                Class.`class` as 'class',
7                Subclass.`sub_class` as 'subclass'
8            from entries Entries
9                INNER JOIN `tasks` Task
10                    ON task_id = Task.id
11                INNER JOIN `task_class` Class
12                    ON Task.`class_id` = Class.`id`
13                INNER JOIN `task_subclasses` Subclass
14                    ON Task.`subclass_id` = Subclass.`id`
15                WHERE Entries.`opportunity_id` = '".$opportunity->id."'
16                GROUP BY Entries.`task_id`"
17    );
18Entries
19Tasks
20Class
21Subclass
22Entries::with(['Tasks','Class','Subclass'])->get();
23

from this, you will get all objects from this array

Let just say

The class have a relation with another Model but not Entries table then the Eloquent is something like this

1    $timeBreakDown = DB::select(
2        "SELECT
3                Entries.`task_id`,
4                Entries.`opportunity_id`,
5                SUM(Entries.`total_duration`) as 'duration',
6                Class.`class` as 'class',
7                Subclass.`sub_class` as 'subclass'
8            from entries Entries
9                INNER JOIN `tasks` Task
10                    ON task_id = Task.id
11                INNER JOIN `task_class` Class
12                    ON Task.`class_id` = Class.`id`
13                INNER JOIN `task_subclasses` Subclass
14                    ON Task.`subclass_id` = Subclass.`id`
15                WHERE Entries.`opportunity_id` = '".$opportunity->id."'
16                GROUP BY Entries.`task_id`"
17    );
18Entries
19Tasks
20Class
21Subclass
22Entries::with(['Tasks','Class','Subclass'])->get();
23Entries::with(['Tasks','Class.Subclass'])->get();
24

hope its helpful for you

Source https://stackoverflow.com/questions/70318632

QUESTION

PHP Serial connection read timeout

Asked 2021-Dec-05 at 12:15

I'm trying to figure something out here

I have a 'sequence' to be executed via a serial port (on an RPI).

I have an supervisored PHP command in Laravel running that connects to a MQTT broker.

When I send a message to that broker, the RPI picks it up and processes it. Now, I have a moment in which I wait for user interaction. The issue here is, sometimes the user does not interact with the system and the PI keeps "waiting" for serial data. When a user presses a button, I get serial data, which I can process.

I tried to use a while (true) {} loop that reads the serial data, but it just stops suddenly. Here is some example code;

1$configure = new TTYConfigure();
2$configure->removeOption("9600");
3$configure->setOption("115200");
4
5$this->serialPort = new SerialPort(new SeparatorParser("\n"), $configure);
6
7$serialDevice = config('app.device_type') === 'usb' ? '/dev/ttyACM0' : '/dev/ttyAMA0';
8
9$this->serialPort->open($serialDevice);
10
11// this is a special one, we add an timeout here of 15 seconds, to prevent that the machine would get stuck.
12$timeoutStart = time();
13$timeout = $timeoutStart + 15; // 15 seconds of timeout.
14$aborted = false;
15
16while (true) {
17    $data2 = $this->serialPort->read();
18
19    if (Str::contains($data2, "Whatever I want to check for")) {
20        // Process the data and get out of this loop via a 'break;' statement
21    }
22
23
24    // check if 15 seconds have passed, if so, then we want to stop the vend sequence.
25    if (time() >= $timeout) {
26        $this->serialPort->write("C,STOP\n"); // STOP vending
27        $aborted = true;
28        $this->alert("vending sequence stopped");
29    }
30}
31

When I place logs in the true loop, I see it loops, but suddenly stops looping (I bet it's the $data2 = $this->serialPort->read(); that just "stops" reading or keeps reading the serial port.

I want to be able to kill the loops and do an API call to revert some changes that hapend before that action.

Is this possible? If so how?

Packages I use:

  • Laravel lumen
  • PhpMqtt
  • lepiaf\SerialPort

ANSWER

Answered 2021-Dec-05 at 12:15

If you look at the source of lepiaf\SerialPort you'll find it sets the stream in non blocking mode, however the read method does an infinite loop until it finds the separator. This means it will never return unless the separator is received, and depending on your configuration your script will be killed once the php max execution time is reached. Since the library is very simple the better option is to edit the read method adding a timeout parameter. Edit the file "lepiaf/SerialPort/SerialPort.php", scroll down to the read method (line 107) and change it as follows:

1$configure = new TTYConfigure();
2$configure->removeOption("9600");
3$configure->setOption("115200");
4
5$this->serialPort = new SerialPort(new SeparatorParser("\n"), $configure);
6
7$serialDevice = config('app.device_type') === 'usb' ? '/dev/ttyACM0' : '/dev/ttyAMA0';
8
9$this->serialPort->open($serialDevice);
10
11// this is a special one, we add an timeout here of 15 seconds, to prevent that the machine would get stuck.
12$timeoutStart = time();
13$timeout = $timeoutStart + 15; // 15 seconds of timeout.
14$aborted = false;
15
16while (true) {
17    $data2 = $this->serialPort->read();
18
19    if (Str::contains($data2, "Whatever I want to check for")) {
20        // Process the data and get out of this loop via a 'break;' statement
21    }
22
23
24    // check if 15 seconds have passed, if so, then we want to stop the vend sequence.
25    if (time() >= $timeout) {
26        $this->serialPort->write("C,STOP\n"); // STOP vending
27        $aborted = true;
28        $this->alert("vending sequence stopped");
29    }
30}
31public function read($maxElapsed = 'infinite')
32{
33    $this->ensureDeviceOpen();
34    
35    $chars = [];
36    $timeout = $maxElapsed == 'infinite' ? 1.7976931348623E+308 : (microtime(true) + $maxElapsed);
37    do {
38        $char = fread($this->fd, 1);
39        if ($char === '') {
40            if (microtime(true) > $timeout) return false;
41            usleep(100);    //Why waste CPU?
42            continue;
43        }
44        $chars[] = $char;
45    } while ($char !== $this->getParser()->getSeparator());
46
47    return $this->getParser()->parse($chars);
48}
49

Then in your code call the method as:

1$configure = new TTYConfigure();
2$configure->removeOption("9600");
3$configure->setOption("115200");
4
5$this->serialPort = new SerialPort(new SeparatorParser("\n"), $configure);
6
7$serialDevice = config('app.device_type') === 'usb' ? '/dev/ttyACM0' : '/dev/ttyAMA0';
8
9$this->serialPort->open($serialDevice);
10
11// this is a special one, we add an timeout here of 15 seconds, to prevent that the machine would get stuck.
12$timeoutStart = time();
13$timeout = $timeoutStart + 15; // 15 seconds of timeout.
14$aborted = false;
15
16while (true) {
17    $data2 = $this->serialPort->read();
18
19    if (Str::contains($data2, "Whatever I want to check for")) {
20        // Process the data and get out of this loop via a 'break;' statement
21    }
22
23
24    // check if 15 seconds have passed, if so, then we want to stop the vend sequence.
25    if (time() >= $timeout) {
26        $this->serialPort->write("C,STOP\n"); // STOP vending
27        $aborted = true;
28        $this->alert("vending sequence stopped");
29    }
30}
31public function read($maxElapsed = 'infinite')
32{
33    $this->ensureDeviceOpen();
34    
35    $chars = [];
36    $timeout = $maxElapsed == 'infinite' ? 1.7976931348623E+308 : (microtime(true) + $maxElapsed);
37    do {
38        $char = fread($this->fd, 1);
39        if ($char === '') {
40            if (microtime(true) > $timeout) return false;
41            usleep(100);    //Why waste CPU?
42            continue;
43        }
44        $chars[] = $char;
45    } while ($char !== $this->getParser()->getSeparator());
46
47    return $this->getParser()->parse($chars);
48}
49$data2 = $this->serialPort->read(15);
50if ($data2 === false) {
51    //Timeout occurred
52} elseif (Str::contains($data2, "Whatever I want to check for")) {
53    //String found
54} else {
55    //Data received but string not found
56}
57

Source https://stackoverflow.com/questions/69750212

QUESTION

Laravel 8 ConsoleTvs 7 - Apply dataset configuration through extra argument of advancedDataset method

Asked 2021-Oct-29 at 10:53

I am sending my data to the front-end of ConsoleTvs 7 Chartisan chart using the built in back-end advancedDataset method. As the third parameter I decided to send extra dataset configurations in array data type:

1// Example of extra info data that forms part of chartData return
2$data['extra'] = ['type' => 'line', 'fill' => false, 'borderColor' => '#FF6F6F', 'backgroundColor' => '#FF6F6F', 'hidden' => true,
3                                'datalabels' => ['display' => true], 'borderDash' => [5, 5]];
4
1// Example of extra info data that forms part of chartData return
2$data['extra'] = ['type' => 'line', 'fill' => false, 'borderColor' => '#FF6F6F', 'backgroundColor' => '#FF6F6F', 'hidden' => true,
3                                'datalabels' => ['display' => true], 'borderDash' => [5, 5]];
4//--> within handler method
5public function handler(Request $request): Chartisan
6{
7    $data = $this->chartData($request);  // Trait method chartData return
8
9    $chart = Chartisan::build()
10        ->labels($data["labels"]);
11    
12    foreach ($data['dataset'] as $key => $values) {
13        $chart->advancedDataset($values['legend'], $values['data'], $values['extra']);
14     //                                                                    ^
15     //-----------------------------  -------------------------------------| extra arg
16    }
17
18    return $chart;
19}
20

This extra values are not applied to the datasets configuration. In fact the chart renders its default bar chart if I remove the ChartisanHooks.datasets(...[ configurations ]...) method.

How can I apply the extra dataset configs to the front-end without having to resort to double work? Is there a setting I am missing or how do I access the extra argument?

Laravel 8
Chart.js v2.9.4
chartjs-plugin-datalabels v1.0.0

ANSWER

Answered 2021-Oct-29 at 10:53

At last I found the answer in the not so obscure Chartisan documentation.
The custom() method of the front-end const hooks = new ChartisanHooks() instance contains 3 hook parameters namely :

1// Example of extra info data that forms part of chartData return
2$data['extra'] = ['type' => 'line', 'fill' => false, 'borderColor' => '#FF6F6F', 'backgroundColor' => '#FF6F6F', 'hidden' => true,
3                                'datalabels' => ['display' => true], 'borderDash' => [5, 5]];
4//--> within handler method
5public function handler(Request $request): Chartisan
6{
7    $data = $this->chartData($request);  // Trait method chartData return
8
9    $chart = Chartisan::build()
10        ->labels($data["labels"]);
11    
12    foreach ($data['dataset'] as $key => $values) {
13        $chart->advancedDataset($values['legend'], $values['data'], $values['extra']);
14     //                                                                    ^
15     //-----------------------------  -------------------------------------| extra arg
16    }
17
18    return $chart;
19}
20hooks.custom(({ data, merge, server }) => {
21  // data ->   Contains the current chart configuration
22  //           data that will be passed to the chart instance.
23  // merge ->  Contains a function that can be called to merge
24  //           two javascript objects and returns its merge.
25  // server -> Contains the server information in case you need
26  //           to acces the raw information provided by the server.
27  //           This is mostly used to access the `extra` field.
28
29  // ...
30
31  // The function must always return the new chart configuration.
32  return data
33})
34

The aptly named server key contains a datasets key that consists of an array of objects where one key is named extra i.e.

1// Example of extra info data that forms part of chartData return
2$data['extra'] = ['type' => 'line', 'fill' => false, 'borderColor' => '#FF6F6F', 'backgroundColor' => '#FF6F6F', 'hidden' => true,
3                                'datalabels' => ['display' => true], 'borderDash' => [5, 5]];
4//--> within handler method
5public function handler(Request $request): Chartisan
6{
7    $data = $this->chartData($request);  // Trait method chartData return
8
9    $chart = Chartisan::build()
10        ->labels($data["labels"]);
11    
12    foreach ($data['dataset'] as $key => $values) {
13        $chart->advancedDataset($values['legend'], $values['data'], $values['extra']);
14     //                                                                    ^
15     //-----------------------------  -------------------------------------| extra arg
16    }
17
18    return $chart;
19}
20hooks.custom(({ data, merge, server }) => {
21  // data ->   Contains the current chart configuration
22  //           data that will be passed to the chart instance.
23  // merge ->  Contains a function that can be called to merge
24  //           two javascript objects and returns its merge.
25  // server -> Contains the server information in case you need
26  //           to acces the raw information provided by the server.
27  //           This is mostly used to access the `extra` field.
28
29  // ...
30
31  // The function must always return the new chart configuration.
32  return data
33})
34server.datasets[0].extra // all array key : values passed from server
35

Hoorah!

So to access this extra key : values I pass them to the front-end hooks.custom() method data.datasets[0] object or create new ones e.g.

1// Example of extra info data that forms part of chartData return
2$data['extra'] = ['type' => 'line', 'fill' => false, 'borderColor' => '#FF6F6F', 'backgroundColor' => '#FF6F6F', 'hidden' => true,
3                                'datalabels' => ['display' => true], 'borderDash' => [5, 5]];
4//--> within handler method
5public function handler(Request $request): Chartisan
6{
7    $data = $this->chartData($request);  // Trait method chartData return
8
9    $chart = Chartisan::build()
10        ->labels($data["labels"]);
11    
12    foreach ($data['dataset'] as $key => $values) {
13        $chart->advancedDataset($values['legend'], $values['data'], $values['extra']);
14     //                                                                    ^
15     //-----------------------------  -------------------------------------| extra arg
16    }
17
18    return $chart;
19}
20hooks.custom(({ data, merge, server }) => {
21  // data ->   Contains the current chart configuration
22  //           data that will be passed to the chart instance.
23  // merge ->  Contains a function that can be called to merge
24  //           two javascript objects and returns its merge.
25  // server -> Contains the server information in case you need
26  //           to acces the raw information provided by the server.
27  //           This is mostly used to access the `extra` field.
28
29  // ...
30
31  // The function must always return the new chart configuration.
32  return data
33})
34server.datasets[0].extra // all array key : values passed from server
35const chart = new Chartisan({
36  el: '#test_chart',
37  hooks: new ChartisanHooks()
38    .colors()
39    .custom(function({ data, merge, server }) { // server param
40
41     //---> loop through extra from server
42     for (let i = 0; i < server.datasets.length; i++) {
43         const extras = server.datasets[i].extra; // extra object
44         for (const [key, value] of Object.entries(extras)) { // loop through extras
45             data.data.datasets[i][key] = value; // add extras to data
46         }
47                    
48     }
49      return merge(data, { // merge data
50        options: {
51          layout: {
52            padding: {
53              left: 0,
54              right: 0,
55              top: 50,
56              bottom: 0
57            },
58          },
59          aspectRatio: 1,
60          maintainAspectRatio: false,
61          responsive: true,
62          legend: {
63            display: true,
64            position: 'top',
65            labels: {
66              usePointStyle: true,
67              fontSize: 12,
68            },
69          },
70          elements: {
71            point: {
72              pointStyle: 'circle',
73            }
74          },
75          scales: {
76            xAxes: [{
77              maxBarThickness: 120,
78              scaleLabel: {
79                display: true,
80                labelString: "xAxes_label"
81              },
82              gridLines: {
83                display: false
84              },
85              ticks: {
86                fontSize: 10,
87                maxRotation: 80,
88                minRotation: 80,
89                padding: 2
90              },
91            }],
92            yAxes: [{
93              scaleLabel: {
94                display: true,
95                labelString: "yAxes_label"
96              },
97              gridLines: {
98                display: false,
99                drawBorder: false
100              },
101              ticks: {
102                display: true,
103                fontSize: 10,
104                suggestedMin: 0
105              },
106            }],
107          },
108          plugins: {
109            datalabels: {
110              color: '#ff0a6c',
111              labels: {
112                title: {
113                  font: {
114                    weight: 'bold',
115                    size: 11,
116                  }
117                },
118                value: {
119                  color: 'green'
120                }
121              },
122              formatter: function(value, context) {
123                return (value != '' && value !== undefined) ? Math.round(value * 100) / 100 : value;
124              },
125              anchor: 'end',
126              align: 'start',
127              display: 'auto',
128              clamp: false
129            }
130          }
131        }
132      });
133    }),
134});
135

Of course this is very rough and needs checking if client side supports some of these methods. Also server.datasets[i].extra !== null, object[key] !== undefined etcetera checks is also needed.

This of course makes this more dynamic from back-end. The question is, is ConsoleTvs package dead as a back-end safe Laravel package and is it still supported by its developer.

Source https://stackoverflow.com/questions/69620329

QUESTION

What is the "Add #[Pure] attribute" inspection in PhpStorm checking for?

Asked 2021-Oct-06 at 18:09

I've got a very simple FormRequest class in a Laravel project. Two methods, both of which return a simple array that's partially populated by a method, but the IDE treats them differently.

1<?php
2
3namespace App\Http\Requests;
4
5class VerifyPhoneNumber extends FormRequest {
6    use Support\ValidatesPhoneNumbers;
7
8    public function authorize(): bool {
9        return true;
10    }
11
12    public function rules(): array {
13        return [
14            "phone_number" => $this->getPhoneNumberRules(),
15            "verify_code" => ["required", "numeric", "max:999999"],
16        ];
17    }
18
19    public function messages(): array {
20        return [
21            "phone_number.regex" => $this->getPhoneNumberMessage(),
22        ];
23    }
24}
25

And the very basic trait methods:

1<?php
2
3namespace App\Http\Requests;
4
5class VerifyPhoneNumber extends FormRequest {
6    use Support\ValidatesPhoneNumbers;
7
8    public function authorize(): bool {
9        return true;
10    }
11
12    public function rules(): array {
13        return [
14            "phone_number" => $this->getPhoneNumberRules(),
15            "verify_code" => ["required", "numeric", "max:999999"],
16        ];
17    }
18
19    public function messages(): array {
20        return [
21            "phone_number.regex" => $this->getPhoneNumberMessage(),
22        ];
23    }
24}
25<?php
26
27namespace App\Http\Requests\Support;
28
29trait ValidatesPhoneNumbers {
30    protected function getPhoneNumberMessage(): string {
31        return __("Some localized error message");
32    }
33
34    protected function getPhoneNumberRules(): array {
35        return ["regex:/^\+?1?[2-9][0-9]{5,14}$/", "max:16"];
36    }
37}
38

The thing I'm puzzled about is that the IDE inspection complains that I should add the JetBrains\PhpStorm\Pure attribute to the rules() method, but not the messages() method.

The comments in the class definition say:

The attribute marks the function that has no impact on the program state or passed parameters used after the function execution. This means that a function call that resolves to such a function can be safely removed if the execution result is not used in code afterwards.

That doesn't really give me any clues why it treats these two methods differently. If I'm understanding the second sentence correctly, when the result of a "pure" method is unused the IDE will flag usage of the method as unused and recommend its removal.

What is the logic used to determine when this attribute is needed?

ANSWER

Answered 2021-Oct-06 at 17:41

If a function only depends on other pure functions, then it is also pure. Since getPhoneNumberRules() just returns a fixed array, it's pure, so rules() is also pure.

But messages() calls getPhoneNumberMessage(), which calls the __() function that can return a different localized message if the location state changes, so it's not pure.

Source https://stackoverflow.com/questions/69470268

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Laravel

Tutorials and Learning Resources are not available at this moment for Laravel

Share this Page

share link

Get latest updates on Laravel