ahoi

ahoi

Member Since 1 Year Ago

Experience Points
3,980
Total
Experience

1,020 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
3,980 XP
Oct
19
2 days ago
Activity icon

Started a new Conversation Get ID Of Saved Pivot-item

Hello,

I would like to solve the following problem:

I have a model (Car) that is loaded as a relation to another model (Driver) with a pivot table.

Car -> belongsToMany Driver (with pivot) -> belongsToMany Accessoires (with Pivot).

The model in turn has relations (accessories) that are loaded with pivot.

The problem: The model Accessories has two pivot tables which can be loaded depending on other factors. If the model Accessories is loaded as a relation of Driver as a relation of Car, the pivot tables should be output correctly.

This is what it looks like at the moment:

 collect($request->input('data.driver'))->each(function ($driver) use
        (
            $car
        ) {
            
            $ndriver = Driver::findOrFail($driver['id']);
            
            $added = $car->driver()->save($driver, [
                'custom' => $driver['custom'],
                title' => $driver['title'],
                factor' => $driver['factor'],
            ]);
                        
            /*Save attributes*/
            $added->syncDriverAttributes($driver['attributes']],
                $car->id);
        });

Now I should actually specify in $added->syncDriverAttributes($driver['attributes'], $car->id); the pivot ID of the created pivot data in $added. Unfortunately I can't find out what the pivot ID is at the moment, because it is not returned in $added.

The problem: I can't find out the last pivot ID from the timestamp either, because all entries have the same timestamp.

So my question is: How can I solve that?

Oct
16
5 days ago
Activity icon

Started a new Conversation Eloquent Resource With Two Possible Pivot Tables - Elegant Way To Return Values

Hello everybody,

I got a resource that comes with two possible pivots. Now I'd like to add values depending on which pivot is loaded.

This is how I am doing it at the moment:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\PotentiallyMissing;


class CarAttributeResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'         => $this->id,
            'title'      => ($title
                = $this->whenPivotLoaded('car_car_attribute',
                function () {
                    return (boolean)$this->pivot->custom === true
                        ? $this->pivot->title : $this->title;
                })) instanceof PotentiallyMissing
            && $title->isMissing() ? (($title_ppa
                = $this->whenPivotLoaded('car_bundle_car_bundle_attribute',
                function () {
                    return (boolean)$this->pivot->custom === true
                        ? $this->pivot->title : $this->title;
                })) instanceof PotentiallyMissing
            && $title_ppa->isMissing() ? $this->title : $title_ppa) : $title,
        ];
    }
}

Does not look nice at all, right?

Do you guys see any possibilities to make this more elegant and readable?

Oct
15
6 days ago
Activity icon

Replied to Cannot Add Foreign Key Constraint - But Why?

D'oh 🙈 Too stupid again. Thanks 👍

Activity icon

Replied to Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row

Thanks, that was exactly my problem 🙈

Activity icon

Started a new Conversation Cannot Add Foreign Key Constraint - But Why?

Hello everybody,

I got this table schema:

public function up()
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('category_id')->nullable();
            $table->string('title');
            $table->softDeletes();
            $table->timestamps();
        });
    }

Now I'd like to add this table with this schema:

 Schema::create('drivers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('car_id');
            $table->foreign('car_id')->references('id')
                ->on('cars')->onDelete('cascade');
            $table->timestamps();
        });

Shouldn't be a problem, right?

But it is:

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table drivers add constraint drivers_car_id_foreign foreign key (car_id) references cars (id) on delete cascade)

The cars table is created before the drivers table but still I'm getting this error.

Oct
14
1 week ago
Activity icon

Started a new Conversation Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row

Hi there,

i got the following problem:

I would like to create a model entry with pivot. While saving this, I am getting this error:

 "message": "SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
    (`homestead`.`product_bundle_product_product_bundle_product_attribute`, CONSTRAINT `pb_product_attribute` FOREIGN KEY
    (`product_bundle_product_attribute_id`) REFERENCES `product_bundle_product_)
    (SQL: insert into `product_bundle_product_product_bundle_product_attribute`
    (`custom`, `price`, `product_bundle_product_attribute_id`, `product_bundle_product_id`, `title`, `type`, `unit`, `value`)
    values (1, 2, 1, 1, Test, decimal, GB, 16))",
    "exception": "Illuminate\Database\QueryException",
    "file": "/home/vagrant/code/vendor/laravel/framework/src/Illuminate/Database/Connection.php",
    "line": 665,

This is the migration that belongs to this:

Schema::create('product_bundle_product_product_bundle_product_attribute', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('product_bundle_product_id')->unsigned();
            $table->bigInteger('product_bundle_product_attribute_id')
                ->unsigned();
            $table->boolean('custom')->nullable();
            $table->string('title')->nullable();
            $table->string('unit')->nullable();
            $table->string('type')->nullable();
            $table->text('value')->nullable();
            $table->float('price')->nullable();
            $table->foreign('product_bundle_product_id', 'pb_product')
                ->references('id')
                ->on('product_bundle_products')->onDelete('cascade');
            $table->foreign('product_bundle_product_attribute_id', 'pb_product_attribute')
                ->references('id')
                ->on('product_bundle_product_attributes')
                ->onDelete('cascade');
        });

I was able to run the migration without any problems, but once I am trying to sync this, I am getting the error above.

This is my sync-statement:

        $result = [ 1 => [
            'custom' => true,
            'title' => "Test",
            'unit' => 'GB',
            'type' => "decimal",
            'price' => 2,
            'value' => 16
        ]];

 $this->productAttributes()->sync($result);

I saw in the error message that there's something cut off:

REFERENCES product_bundle_product_ where it should be product_bundle_product_attributes, right?

Oct
13
1 week ago
Activity icon

Started a new Conversation Return Pivot-data Depending On The Context Of The Model (loaded As Relation Or Not?)

Hello,

I'm just thinking about whether it's possible to influence a model to return values depending on which pivot table is loaded.

The Model I am referring to, can be a Product or a Product that is a part of a bundle of products.

Product:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Product extends Model
{
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable
        = [
            'title',
            'price'
        ];
    
    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsToMany
     */
    public function productAttributes()
    {
        return $this->belongsToMany(ProductAttribute::class)
            ->withPivot('value', 'title');
    }
    
    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsToMany
     */
    public function productBundleAttributes()
    {
        return $this->belongsToMany(ProductAttribute::class,
            'product_product_attribute_bundle')
            ->withPivot('value', 'title');
    }
    
}

Each product has several attributes (Model: ProductAttributes). Here, too, each attribute has specific values and a pivot table that indicates which values are to be used for the attribute for a product.

Example

Product:

  • title: Shoe
  • price: $20

ProductAttributes:

  • material: Leather
  • colour: Green

A product can therefore have several attributes (here: material, colour). The product attributes can be defined elsewhere in the and assigned to a new product via the input mask for the product.

In a new product, however, the standard values of the attributes should also be able to be overwritten. Example: The material is leather, but it is a special leather and the title of the attribute is therefore no longer "Leather", but "lamb leather".

To achieve this, each product attribute has a pivot table again.

Now it gets too complicated for me:

If a product belongs to a product bundle, it should also have these pivot tables - but a change to a product attribute within a product bundle should not change the data of the attribute for the actual product. So a product actually has two pivot tables for its attributes:

  • One, if you are in the "product" context
  • One if you are in the "product bundle" context.

Now the question is: Is there a way to see in which context the attribute is located to make the pivot values easier to retrieve? Would it even be possible that

Product -> Attributes -> Leather -> Title automatically returns the title of the product bundle pivot table if you are in the product bundle context or the title of the product pivot table if this is not the case?

Oct
07
2 weeks ago
Activity icon

Started a new Conversation Use Pivot-tables With Different Models

Hello there,

I got the following models:

  • User
  • UserGroup
  • Item

Now every user has a belongsToMany relation to Item with pivot:

    public function items()
    {
        return $this->belongsToMany(Item::class)
            ->withPivot('value');
    }

This is the structure of item:

Item:

  • title
  • pivot:
    • value

Example

User

  • name: Tim
  • items:
    • title: car
    • value: 2

Now it's getting tricky: I'd like to use User also in the model UserGroup - and each User should have many Items with a new pivot table, that's not identical to the pivot table, the Item has, when it's a pivot of User.

Example

UserGroup

  • name: Party-Group
  • users:
    • name: Tim
    • items:
      • title: car
      • value: 3

My approach

So I think, the only possible solution would be to create something like a new model called UserGroupUser (extended from User) with a relation to UserGroupUserItems (extended from Item).

But maybe there's a smarter way to do that?

Oct
06
2 weeks ago
Activity icon

Started a new Conversation Nested Items With Pivot -> Children Do Not Get The Pivot Data

Hello everybody,

I am trying to build a possibility of nested items for my user model.

Actually, every user can have many items, which can have children of their own type (item).

This is the user's relation to item:

   /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsToMany
     */
    public function items()
    {
        return $this->belongsToMany(Item::class)->withPivot( 'value'');
    }

This is how the children are being resolved:

   /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function children()
    {
        return $this->hasMany(Item::class, 'parent_id');
    }

Now - thanks to your help before - I can query the items with children:

$user->items()->whereNull('parent_id')->with('children')->get();

This is the result:

 Illuminate\Database\Eloquent\Collection {#3247
     all: [
       App\Item {#3232
         id: 2,
         parent_id: null,
         title: "Parent 1",
        
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {#3235
           user_id: 12,
           user_item_id: 2,
           value: "3",
         },
         children: Illuminate\Database\Eloquent\Collection {#3267
           all: [
             App\Item {#3270
               id: 3,
               parent_id: 2,
               title: "Child 1",
               created_at: "2019-10-04 14:29:59",
               updated_at: "2019-10-04 14:29:59",
             },
             App\Item {#3272
               id: 4,
               parent_id: 2,
               title: "Child 2",
               created_at: "2019-10-04 14:30:16",
               updated_at: "2019-10-04 14:30:16",
             },
           ],
         },
       },
       App\Item {#3255
         id: 5,
         parent_id: null,
         title: "Parent 2",
         created_at: "2019-10-04 14:36:50",
         updated_at: "2019-10-04 14:36:50",
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {#3240
           user_id: 12,
           user_item_id: 5,
           value: "50",
         },
         children: Illuminate\Database\Eloquent\Collection {#3266
           all: [],
         },
       },
     ],
   }

As you can see, the parent items got an pivot value - the children do not have any pivot data. How can I solve that? I learned, that hasMany does not provide pivot.

Activity icon

Replied to Query For Nested Model Returns Duplicates

Works fine, thanks :-)

Activity icon

Started a new Conversation Query For Nested Model Returns Duplicates

Hallo everybody,

at the moment I am learning a lot about Laravel and eloquent, so please forgive my "stupid" questions.

My goal

I'd like to save nested items and get them later with nested structure

Example:

 Illuminate\Database\Eloquent\Collection {#3246
     all: [
       App\Item {#3254
         id: 2,
         parent_id: null,
         title: "Parent",
         created_at: "2019-10-04 14:22:23",
         updated_at: "2019-10-04 14:22:23",
         children: Illuminate\Database\Eloquent\Collection {#3285
           all: [
             App\Item {#3287
               id: 3,
               parent_id: 2,
               title: "Child 1",
               created_at: "2019-10-04 14:29:59",
               updated_at: "2019-10-04 14:29:59",
             },
             App\Item {#3289
               id: 4,
               parent_id: 2,
               title: "Child 2",
               created_at: "2019-10-04 14:30:16",
               updated_at: "2019-10-04 14:30:16",
             },
           ],
         },
       },
     ],
   }

Current result

My current result is this:

 Illuminate\Database\Eloquent\Collection {#3246
     all: [
       App\Item {#3254
         id: 2,
         parent_id: null,
         title: "Parent",
         created_at: "2019-10-04 14:22:23",
         updated_at: "2019-10-04 14:22:23",
         children: Illuminate\Database\Eloquent\Collection {#3285
           all: [
             App\Item {#3287
               id: 3,
               parent_id: 2,
               title: "Child 1",
               created_at: "2019-10-04 14:29:59",
               updated_at: "2019-10-04 14:29:59",
             },
             App\Item {#3289
               id: 4,
               parent_id: 2,
               title: "Child 2",
               created_at: "2019-10-04 14:30:16",
               updated_at: "2019-10-04 14:30:16",
             },
           ],
         },
       },
       App\Item {#3259
         id: 3,
         parent_id: 2,
         title: "Child 1",
         created_at: "2019-10-04 14:29:59",
         updated_at: "2019-10-04 14:29:59",
         children: Illuminate\Database\Eloquent\Collection {#3282
           all: [],
         },
       },
       App\Item {#3280
         id: 4,
         parent_id: 2,
         title: "Child 2",
         created_at: "2019-10-04 14:30:16",
         updated_at: "2019-10-04 14:30:16",
         children: Illuminate\Database\Eloquent\Collection {#3275
           all: [],
         },
       },
     ],
   }

As you can see, the items are returned as children, but also as single (duplicate) items in the list.

My code

Item

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable
        = [
            'title',
        ];
    
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function parent()
    {
        return $this->belongsTo('App\Item', 'parent_id');
    }
    
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function children()
    {
        return $this->hasMany('App\Item', 'parent_id');
    }
    
}

How I get the related items:

$user->items()->with('children')->get();
Oct
05
2 weeks ago
Activity icon

Started a new Conversation Sync BelongsToMany With Pivot And Nested Children

Hello everybody,

I would like to solve this issue. I got an array like that:

[
  {
    "id": 2,
    "title": "One",
    "parent": {},
    "children": [
      {
        "id": 3,
        "title": "One One",
        "parent": {
          "id": 2,
          "title": "One"
        },
        "children": [],
        "value": 1
      },
      {
        "id": 4,
        "title": "One Two",
        "parent": {
          "id": 2,
          "title": "One"
        },
        "children": [],
        "value": 2
      }
    ],
    "value": 3
  },
  {
    "id": 5,
    "title": "Three",
    "value": 3
  }
]

As you can see, each item can have a child, which can also have a child, which can also have a child and so on. It's nested.

Now I'd like to save these items and each child in a belongsToMany relation with pivot (in this case: value). If I want to use sync(), I would have to prepare all my items in my controller:

 <?php

/*Save $items*/
$items
    = collect($request->input('data.items'))->mapWithKeys(function (
    $item
) {
    
    if (array_key_exists('value', $item)) {
        $value = $item['value'];
    } else {
        $value = null;
    }
    
    return [
        $item['id'] => compact('value'),
    ];
});

$user->items()->sync($items);

But this does not go recursively through all children. I thought about something like that:

/*Save items*/
$items
    = collect($request->input('data.items'))->mapWithKeys(function (
    $item
) {
    $traverse = function ($item) use (&$traverse) {
        if (array_key_exists('value', $item)) {
            $value = $item['value'];
        } else {
            $value = null;
        }
        
        foreach ($item['children'] as $child) {
            $child = $traverse($child);
        }
        
        $children = ($item['children']);
        
        return [
            $item['id'] => compact('value', 'children'),
        ];
    };
    
    $item = $traverse($item);

But this does not work out.

What I want as a result:

  • Save every item as a belongsToMany relation for the user with pivot value
  • Save all children recursively with pivot value
Activity icon

Replied to Resource: Use WhenPivotLoaded As Condition

Hm, this does not work, as $title is not false or null, if there's no pivot, but it's instance of MissingValue .

So this works:

        $title = $this->whenPivotLoaded('item_groups_attribute', function () {
            return $this->pivot->title;
        });
        
        if ($title instanceof \Illuminate\Http\Resources\MissingValue) {
            $title = $this->title;
        }

So maybe I find a more elegant way, but actually it works - thanks :-)

Activity icon

Replied to Resource: Use WhenPivotLoaded As Condition

Hi and thank you very much,

I tried that, but if there's no pivot, the title does not appear in fields:

{
  "data": {
    "id": 2
  }
}

This is the response if loaded with pivot:

{
  "data": {
    "id": 5,
    "title": "Test"
  }
}
Oct
04
2 weeks ago
Activity icon

Started a new Conversation Resource: Use WhenPivotLoaded As Condition

Hello everybody,

I'm just don't get, how to solve this problem, so the community can be my hero :-)

I would like to have this:

  • A collection returns 'title' => $this->title when it's loaded without a pivot
  • A collection returns title => $this->pivot->title . "Hello World" when it's loaded with pivot.

This is my approach:

<?php

namespace App\Http\Resources;

use App\Item;
use Illuminate\Http\Resources\Json\JsonResource;


class ItemResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        
        return [
            'id'     => $this->id,
            'title'  => $this->whenPivotLoaded('item_groups_attribute',
                function () {
                    return $this->pivot->title . "Hello";
                }), // but how to add $this->title, if it's not with pivot?
        ];
    }
}
Oct
01
2 weeks ago
Activity icon

Replied to Where Are You All From?

Cheers from Göttingen, Germany 😊

Aug
14
2 months ago
Activity icon

Started a new Conversation Validator: Numeric And Require_unless

Hello everybody,

I got these validation rules:

'data.items'               => 'nullable|array',
'data.items.*.value'       => 'required_unless:data.interval,0|sometimes|numeric',

So I read it as follows: If data.interval is not 0, the array's field value is required and the input should be numeric.

What happens: If the value is empty and data.interval is 0, the validation fails, because the validator expects a numeric value.

But shouldn't sometimes prevent this behavior?

Aug
12
2 months ago
Activity icon

Replied to Php Artisan Schedule:run No Scheduled Commands Are Ready To Run.

Aaaah, okay - I did not know that. How about the between() method? If I do a between('04:30', '23:50'): How does the scheduler decide to run a scheduled command?

Activity icon

Replied to Php Artisan Schedule:run No Scheduled Commands Are Ready To Run.

Hi @nakov

But if the cron does not run and I run schedule:run manually (lets say at 4pm), all jobs that have not been processed yet are not being run?

Activity icon

Replied to Laravel Scheduling Not Firing Command

@mulugu: Are you sure? I don't think the queue listener is necessary to run scheduled tasks. That's why you create the cronjob.

Correct me, if I am wrong.

Activity icon

Replied to Php Artisan Schedule:run No Scheduled Commands Are Ready To Run.

Hi,

thank you for your replies.

The problem is: Midnight is over now and if I perform schedule:run there are still no scheduled items available.

Aug
11
2 months ago
Activity icon

Started a new Conversation Php Artisan Schedule:run No Scheduled Commands Are Ready To Run.

Hi everybody,

that's a strange situation:

I edited my app/Console/Kernel.php like this:

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands
        = [//
        ];
    
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     *
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('hello:world')->runInBackground()->daily();
    }
    
    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
        
        require base_path('routes/console.php');
    }
}

hello:world is defined app/Console/Commands/HelloWorld.php:

<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Console\Command;
use App\Hello;

class HelloWorld extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'hello:world';
    
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Say hello to the world';
    
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
    
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $model = new Hello();
        $data    = $model->doStuff();
        
        if (!$data) {
            $this->warn('Did not work out');
            
            return false;
        }
        
        $this->info('Hello worldd');
        return true;
    }
}

I did this before running:

php artisan cache:clear && php artisan clear-compiled && composer --dump-autoload, but if I do php artisan schedule:run I get

No scheduled commands are ready to run.

What did I miss?

Edit: everyMinute() instead of daily() works... That's strange... What can I do to make daily() work?

Aug
05
2 months ago
Activity icon

Replied to Creating-Observer Does Not Save Modifications?

Solved it using created event. In this event I am saving the item directly.

Activity icon

Started a new Conversation Creating-Observer Does Not Save Modifications?

Hello everybody,

I created a little observer to add values to an item once it's created:

 public function creating (Item $item)
    {
        $item->test = 'test';
    }

If I do this:

>>> Item::create(['content' => 'test 123']);

The result is (as expected):

{
  "id": "861c21d8-4526-4b43-9139-c95cd4894497",
  "content": "test 123",
  "test": "test"
}

But if I then do:

Item::first()

The result is:

{
  "id": "861c21d8-4526-4b43-9139-c95cd4894497",
  "content": "test 123",
  "test": null
}

So the changes are not saved. Do I really have to do something like

$item = Item::create(['content' => 'test 123']);
$item->save();

?

Jul
31
2 months ago
Activity icon

Started a new Conversation Validation: Required_unless Or Required_if With Multiple Fields

Hi everybody,

is there a way to validate a field, only if another field's value is not A OR B?

 'data.field'            => 'required_unless:data.field,A|nullable|string|max:255',

checks only one value.

Jul
15
3 months ago
Activity icon

Replied to Set Radio-button Value By Bool In Array

Hi,

yes, that's what I did in the meantime. So we both had the same idea :-)*

I also added a small logic to the mount:

mounted () {
            let vm = this;
            if (_.isEmpty (selected)) {
                _.each (vm.options, function (option) {
                    if (option.value === true) {
                        vm.selected = option.id;
                    }
                });
            }
        }
Activity icon

Replied to Set Radio-button Value By Bool In Array

Hi,

that does work, but unfortunately I need the data structure to be like that.

I just saw an example that could work with Vue, too:

https://codepen.io/thompsonemerson/pen/jPvgoy

But somehow this also does not feel right ;-) Maybe you have better ideas how to solve this with this data-structure?

Activity icon

Replied to Set Radio-button Value By Bool In Array

Hi and thank you very much.

Unfortunately this is not working :-( If I remove :value="true", the option.value is set to null once I select one radio option.

You can check out the codepen or even fork it if you want to :-)

Activity icon

Started a new Conversation Set Radio-button Value By Bool In Array

I'd like to solve the following problem:

I got a data structure like that:

{
  "options": [
    {
      "id": 1,
      "title": "Car",
      "value": true
    },
    {
      "id": 2,
      "title": "Bike",
      "value": false
    },
    {
      "id": 3,
      "title": "Bus",
      "value": false
    }
  ]
}

Now I'd like to show a radio button for each option:

<div v-for="(option,index) in options" :key="index">
    <input type="radio" :id="index" :value="true" :name="'option-selected'" v-model="option.value">
    <label :for="index">{{option.title}}</label>
</div>

Result

I can click every radio button and every option.value is set to true.

My goal

Allow only one radio button to be true. Select Car to be true, as it's set on initial data. Unfortunately I can not use a select or something like that, because the user should be able to edit the title of each option, even without selecting it.

Now my question:

I guess I could use a watcher to watch options and watch for a change in value and unset all other values. But is this the best option?

Example

Here's an example that shows the problem: https://codepen.io/spqrinc/pen/NZZbjZ

Activity icon

Replied to Dynamic Custom Fields: JSON, Pivot, MorphToMany?

I checked out the package, but I missed one thing: You can not delete your attributes.

I decided to use pivot to solve this:

/**
     * @return \Illuminate\Database\Eloquent\Relations\belongsToMany
     */
    public function fields()
    {
        return $this->belongsToMany(CustomField::class)->withPivot('value');
    }
Activity icon

Replied to "Nested Pagination": Paginate (sub-)item In ApiResource

Thanks for your reply :-)

Actually I was asking for a "Laravel-like" solution for that to prevent custom coding. As I don't see a better solution, I guess I have to write my own pagination method for that :-)

Jul
11
3 months ago
Activity icon

Started a new Conversation "Nested Pagination": Paginate (sub-)item In ApiResource

Hello everybody,

I got an ApiResource like this:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Gate;


class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'     => $this->id,
            'name'   => $this->name,
            'email'  => $this->email,
            'status' => $this->status,
        ];
    }
    
}

Now I'd like to add a relation to this: Items:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Gate;


class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'     => $this->id,
            'name'   => $this->name,
            'email'  => $this->email,
            'items'  => new ItemResourceCollection
            ($this->items()->paginate(5)),
            'status' => $this->status,
        ];
    }
    
}

This is ItemResourceCollection:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;


class ItemResourceCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'current_page'   => $this->resource->currentPage(),
            'first_page_url' => $this->resource->url(1),
            'from'           => $this->resource->firstItem(),
            'last_page'      => $this->resource->lastPage(),
            'last_page_url'  => $this->resource->url($this->lastPage()),
            'next_page_url'  => $this->resource->nextPageUrl(),
            'per_page'       => $this->resource->perPage(),
            'prev_page_url'  => $this->resource->previousPageUrl(),
            'to'             => $this->resource->lastItem(),
            'total'          => $this->resource->total(),
            'data'           => $this->collection->transform(function ($item) {
                return [
                    'id'          => $item->id,
                    'title'       => $item->title,
                    'status'      => $item->status,
                ];
            }),
        ];
    }
}

Well - this is the result:

{
  "data": {
    "id": 1,
    "name": "John Doe",
    "email": "[email protected]",
    "items": {
      "current_page": 1,
      "first_page_url": "http://example.org/api/user/1?page=1",
      "from": 1,
      "last_page": 1,
      "last_page_url": "http://example.org/api/user/1?page=1",
      "next_page_url": null,
      "per_page": 5,
      "prev_page_url": null,
      "to": 1,
      "total": 1,
      "data": [
        {
          "id": 1,
          "title": "Test",
          "description": "<p>Test</p>",
          "status": "published"
        }
      ]
    },
    "status": "active"
  }
}

Hm, it seems that this does not really work, because the page-urls are referring the parent model and not the relation?

I would love to see something like: http://example.org/api/user/items?page=1 or something like that and fetch the results using Axios on my frontend:

axios.get ('/api/user/items?page=' + this.pagination.current_page + '&length=' + this.pagination.per_page);

Any idea whether this is possible?

Otherwise I would have to create a route for /user/items/index or something like that and return data from there.

Jul
03
3 months ago
Activity icon

Started a new Conversation Dynamic Custom Fields: JSON, Pivot, MorphToMany?

Hello everybody,

I'm currently working on a "custom fields" feature for my Laravel-app.

What it's supposed to do

Each CustomField should be editable by the user. The CustomField can have a type (string, int, ...) and a value.

Now the created CustomFields can be added to another model (Maybe: User).

Expected result

The values of the custom fields should be callable using something like $user->fields->company->value

It should be easy to iterate through the fields like this: $user->fields()->each(...)

My problem

I'm not sure which way to go: Of course I could just create a model called CustomField and a table with

  • id
  • type

and save them to the User as JSON ($user->fields would be type JSON). But I am not sure, whether this is the best way to go, because I also would like to make the fields searchable later. So maybe pivot is the way to go? Or even morphToMany?

Which way is the most "Laravel-style" way to go?

Thank you for your thoughts (and maybe 1-2 examples ;-) )

Activity icon

Replied to HasMany With Additional Information?

That's a good idea.

Meanwhile I solved it using:

public function productGroups()
    {
        return $this->belongsToMany(ProductGroup::class)->withPivot('discount');
    }

But it's basically the same idea :-)

Jul
02
3 months ago
Activity icon

Started a new Conversation HasMany With Additional Information?

Hello everybody,

I'd like to get the following working:

I got a UserGroup that should have discounts on a list of ProductGroups.

Example:

UserGroup

{
    "data": {
        "id": 2,
        "title": "Test",
        "discounts": null,
    }
}

ProductGroups

{
  "data": [
    {
      "id": 1,
      "title": "Group1"
    },
    {
      "id": 2,
      "title": "Group2"
    }
  ]
}

Expected result

UserGroup

{
  "data": {
    "id": 2,
    "title": "Test",
    "discounts": [
      {
        "productgroup_id": 1,
        "discount": 0
      },
      {
        "productgroup_id": 2,
        "discount": 10
      }
    ]
  }
}

So now I'd like to know: How to save this the best? First I thought about JSON. The problem: If the ProductGroup is being deleted, the UserGroup-discounts-JSON is not updated using a cascade.

Jun
19
4 months ago
Activity icon

Replied to Serverside Breadcrumbs Or Clients Side

Basically, I think that there is nothing against generating the breadcrumbs on the server side. The relevant package has already been mentioned.

If you are planning to build a Vue.js SPA, the question is answered already - it would be best to build a client-side solution.

Conclusion: It depends on what you build and how :-)

Jun
17
4 months ago
Activity icon

Started a new Conversation Validation: String IS NOT

Hello everybody,

I am just writing an update method that should update roles. I would like to prevent a user to choose a reserved name (super-admin).

Is there a validation rule for string IS NOT or do I have to use the regex-rule here?

Jun
16
4 months ago
Activity icon

Started a new Conversation GroupBy And MapToGroups Returns Object In API Resource

Hello everybody,

I am creating an API resource:

public function toArray($request)
    {
        return [
            'permissions' => Permission::all()       
         ];
    }

This is the result Permission::all() in my browser's console:

{
  "data": {
    "permissions": [
      {
        "id": 1,
        "name": "index users",
        "guard_name": "web",
        "created_at": "2019-06-11 06:45:52",
        "updated_at": "2019-06-11 06:45:52"
      },
      {
        "id": 2,
        "name": "create users",
        "guard_name": "web",
        "created_at": "2019-06-11 06:45:52",
        "updated_at": "2019-06-11 06:45:52"
      },
      {
        "id": 3,
        "name": "view users",
        "guard_name": "web",
        "created_at": "2019-06-11 06:45:52",
        "updated_at": "2019-06-11 06:45:52"
      },
      {
        "id": 4,
        "name": "update users",
        "guard_name": "web",
        "created_at": "2019-06-11 06:45:52",
        "updated_at": "2019-06-11 06:45:52"
      },
      {
        "id": 5,
        "name": "delete users",
        "guard_name": "web",
        "created_at": "2019-06-11 06:45:52",
        "updated_at": "2019-06-11 06:45:52"
      },
      {
        "id": 21,
        "name": "index settings",
        "guard_name": "web",
        "created_at": "2019-06-11 06:45:52",
        "updated_at": "2019-06-11 06:45:52"
      },
      {
        "id": 22,
        "name": "view settings",
        "guard_name": "web",
        "created_at": "2019-06-11 06:45:52",
        "updated_at": "2019-06-11 06:45:52"
      },
      {
        "id": 23,
        "name": "update settings",
        "guard_name": "web",
        "created_at": "2019-06-11 06:45:52",
        "updated_at": "2019-06-11 06:45:52"
      }
    ]
  }
}

I would like to an array like this:

[
{ 'group': 'users', 'view': true, 'edit': false, 'create': true, 'delete':
true },
{ 'group': 'settings', 'view': true, 'edit': false, 'create': true, 'delete':
true },
]

This is what I got so far:

Permission::all()->mapToGroups(function
            ($item){
                $exploded = explode(' ', $item->name);
                $item->group = $exploded[1];
                $item->verb = $exploded[0];
                $item->can = [$item->verb => true];

                return [$item['group'] => $item['can']];
            })->map(function($group){
                $permission = $group->collapse();
                return $permission;
            })

This is the result in my browser's console:

{
    "data": {
        "permissions": {
            "users": {
                "index": true,
                "create": true,
                "view": true,
                "update": true,
                "delete": true
            },
            "settings": {
                "index": true,
                "view": true,
                "update": true
            }
        }
    }
}

These are my questions:

  • As you can see, the result is an object, not an array. How can I change it to an array?
  • How can I remove the key ('settings', 'user', ...) and move them to the single array like in my example?
Jun
14
4 months ago
Activity icon

Started a new Conversation Use Explode In Collection To Group By Second Value

Hello everybody,

I am using spatie/laravel-permission (https://github.com/spatie/laravel-permission) to define permissions and roles.

Now I'd like to create a view which lists all the permissions in a table.

To archive this, I am building an API resource, which should contain:

This is what I want to archive:

permissions: [
        { module: 'User', view: true, create: false, delete: false },
        { module: 'Todo', view: true, create: false, delete: false },
      ],

The name of the permission is always verb-model (view-user, create-user, delete-user, view-todo, create-todo, ...)

So I thought about splitting the name of each Permission using explode.

So I would get:

['view', 'user']
['create', 'user']
['delete', 'user']
...

This array could be grouped in my resource.

So I could do something like:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Spatie\Permission\Models\Permission;


class UserRoleResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'          => $this->id,
            'name'        => $this->name,
            'permissions' => Permission::all()->each(function($permission){
                //return the exploded array
            })
        ];
    }
    
}

But there's maybe an easier way with Laravel?

Thank you for your thoughts about this :-)

Jun
08
4 months ago
Activity icon

Started a new Conversation V-validate On Dynamic Custom Component

Hello everybody,

I am using Vee-validate (https://baianat.github.io/vee-validate/) to validate all my forms. Now I would like to do the following:

In my form the "value" field is a dynamic component, depending on the type of the current object. Type can be integer, string, decimal etc.

So if the type changes, the input changes, too.

This is how I did this:

   <component
                                            :name="'attribute-value'"
                                            v-model="attribute.value"
                                            :is="attribute.type">
                                    </component>

And

import string from '@/components/fields/String'
import integer from '@/components/fields/Integer'
import decimal from '@/components/fields/Decimal'

export default {
        name: 'edit',
        metaInfo: {
        title: 'Edit'
        },
        components: {
            string, integer, decimal
        },
}

Alright - each field should have it's own validation. The integer-field should only allow numbers. So I would like to do this:

<template>
    <b-input
            :id="name"
            :name="name"
            type="number"
            v-validate="{ required: true, numeric: true }"
            :state="errors.has(name) ? 'invalid' : ''"
            :value="value"
            v-on:input="$emit('input',$event)"/>
</template>
<script>
export default {
    name: 'Integer',
    inject: {
        $validator: '$validator'
    },
    props: ['name', 'value'],

    $_veeValidate: {
        name() {
            return this.name;
        },
        value() {
            return this.value;
        }
    },
}
</script>

Unfortunately, there are no errors shown, if I enter something else than a number. And: The submit-method on the parent component does not prevent the submission.

I am thankful for all of your comments :-)

May
30
4 months ago
Activity icon

Replied to Set LC_MONETARY Globally

Hm, that's strange.

I added this to bootstrap/app.php:

setlocale(LC_MONETARY, 'de_DE');
echo money_format('%!n€', 23.50);
var_dump(localeconv());
die;

This is the output:

23.50€
/home/vagrant/code/bootstrap/app.php:15:
array (size=18)
  'decimal_point' => string '.' (length=1)
  'thousands_sep' => string '' (length=0)
  'int_curr_symbol' => string '' (length=0)
  'currency_symbol' => string '' (length=0)
  'mon_decimal_point' => string '' (length=0)
  'mon_thousands_sep' => string '' (length=0)
  'positive_sign' => string '' (length=0)
  'negative_sign' => string '' (length=0)
  'int_frac_digits' => int 127
  'frac_digits' => int 127
  'p_cs_precedes' => int 127
  'p_sep_by_space' => int 127
  'n_cs_precedes' => int 127
  'n_sep_by_space' => int 127
  'p_sign_posn' => int 127
  'n_sign_posn' => int 127
  'grouping' => 
    array (size=0)
      empty
  'mon_grouping' => 
    array (size=0)
      empty

If I run this code in a single PHP code runner, I get:

23,50€array(18) {
  ["decimal_point"]=>
  string(1) "."
  ["thousands_sep"]=>
  string(0) ""
  ["int_curr_symbol"]=>
  string(4) "EUR "
  ["currency_symbol"]=>
  string(2) "Eu"
  ["mon_decimal_point"]=>
  string(1) ","
  ["mon_thousands_sep"]=>
  string(1) "."
  ["positive_sign"]=>
  string(0) ""
  ["negative_sign"]=>
  string(1) "-"
  ["int_frac_digits"]=>
  int(2)
  ["frac_digits"]=>
  int(2)
  ["p_cs_precedes"]=>
  int(1)
  ["p_sep_by_space"]=>
  int(0)
  ["n_cs_precedes"]=>
  int(1)
  ["n_sep_by_space"]=>
  int(0)
  ["p_sign_posn"]=>
  int(1)
  ["n_sign_posn"]=>
  int(1)
  ["grouping"]=>
  array(0) {
  }
  ["mon_grouping"]=>
  array(2) {
    [0]=>
    int(3)
    [1]=>
    int(3)
  }
}

I had to run sudo locale-gen de_DE.UTF-8 on my homestead vm - now it works fine. Thanks a lot!

Activity icon

Started a new Conversation Set LC_MONETARY Globally

Hello,

I would like to migrate this little snippet to Laravel:

function money($value){
    setlocale(LC_MONETARY, 'de_DE');
    return money_format('%!n€', $value);

}

echo money(1620.5);

>> 1.620,50€

Well, now I would like to create a custom blade directive:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('money', function ($value) {
            return "<?php echo money_format('%!n€', $value); ?>";
        });
    }
}

Hm, now I have to set the locale. I created a middleware for this:

<?php

namespace App\Http\Middleware;

use Closure;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        app()->setLocale('de_DE');
        
        return $next($request);
    }
}

And of course I registered that in Kernel.php:

 protected $middleware = [
        \App\Http\Middleware\SetLocale::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
    ];

But this does not seem to affect LC_MONETARY? If I add @money(12.5) to a blade-file, the output is:

12.50EUR and not 12,50EUR as it was expected.

So my question is: How can I set LC_MONETARY correctly?

May
29
4 months ago
Activity icon

Replied to Map() Does Not Create A New Instance But Modifies Collection

Yep, that was my mistake. Thanks a lot for opening my eyes :-) It works as expected now.

Activity icon

Started a new Conversation Map() Does Not Create A New Instance But Modifies Collection

Hello,

I would like to group a collection by a specific key (interval). Before I do that, I would like to search for collection items, where setup > 0 and modify the findings, because I need to set "price" = "setup" for those items. I also need to change the interval, because a setup fee is only paid once.

This is what I did to prepare this:

$collection = collect(json_decode($items));

=> Illuminate\Support\Collection {#3086
     all: [
       {#3076
         +"price": 99,
         +"setup": 15,
         +"interval": 1,
       },
     ],
   }

Alright, now let's search for items with setup costs and create a new collection:

$setups = $collection->where('setup', '>', 0)->map(function (
            $item,
            $key
        ) {
            $item->price          = $item->setup;
            $item->setup          = 0;        
            $item->interval       = 0;        
            return $item;
        });

=> Illuminate\Support\Collection {#3071
     all: [
       {#3076
         +"price": 15,
         +"setup": 0,
         +"interval": 0,
       },
     ],
   }

Hmmmm... Thats not cool. The initial collection #3076 has been modified, but shouldn't map() create a new one?

$collection

=> Illuminate\Support\Collection {#3086
     all: [
       {#3076
         +"price": 15,
         +"setup": 0,
         +"interval": 0,
       },
     ],
   }


$setups

=> Illuminate\Support\Collection {#3071
     all: [
       {#3076
         +"price": 15,
         +"setup": 0,
         +"interval": 0,
       },
     ],
   }

https://laravel.com/docs/5.8/collections#method-map:

Like most other collection methods, map returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use the transform method.

So my questions are:

  • How can I search for $items that have a setup fee and store them in a new collection?
  • Is there a more convenient way to duplicate items that have a setup fee and modify the duplicated value to have the price = setup? As a result I would like to get a grouped array that is grouped by interval. The interval of setup should always be 0;

Thanks for your help :-)

May
14
5 months ago
Activity icon

Started a new Conversation Webpack Chunk Names With Laravel Mix

I'd like to use Webpack chunks with Laravel Mix.

At the moment this list is outputted:

                                               Asset      Size        Chunks             Chunk Names
                                     /entry-point.js  3.37 MiB  /entry-point  [emitted]  /entry-point
                                                0.js  57.9 KiB             0  [emitted]  
                                                1.js  20.7 KiB             1  [emitted]  
                                               10.js  24.2 KiB            10  [emitted]  
                                               11.js  17.8 KiB            11  [emitted]  
                                               12.js  17.3 KiB            12  [emitted]  
                                               13.js  20.3 KiB            13  [emitted]  
                                               14.js  34.3 KiB            14  [emitted]  
                                               15.js  16.3 KiB            15  [emitted]  
                                               16.js  16.3 KiB            16  [emitted]  
                                               17.js  18.8 KiB            17  [emitted]  
                                               18.js  9.34 KiB            18  [emitted]  
                                               19.js  18.2 KiB            19  [emitted]  
                                                2.js   487 KiB             2  [emitted]  
                                               20.js  18.2 KiB            20  [emitted]  
                                               21.js  17.2 KiB            21  [emitted]  
                                               22.js  13.3 KiB            22  [emitted]  
                                               23.js    54 KiB            23  [emitted]  
                                               24.js  53.8 KiB            24  [emitted]  
                                               25.js  17.9 KiB            25  [emitted]  
                                               26.js  23.6 KiB            26  [emitted]  
                                               27.js  29.4 KiB            27  [emitted]  
                                               28.js  29.4 KiB            28  [emitted]  
                                               29.js  19.5 KiB            29  [emitted]  
                                                3.js   128 KiB             3  [emitted]  
                                               30.js    17 KiB            30  [emitted]  
                                               31.js  13.1 KiB            31  [emitted]  
                                               32.js  33.4 KiB            32  [emitted]  
                                                4.js   104 KiB             4  [emitted]  
                                                5.js  70.1 KiB             5  [emitted]  
                                                6.js  82.9 KiB             6  [emitted]  
                                                7.js  89.1 KiB             7  [emitted]  
                                                8.js   959 KiB             8  [emitted]  
                                                9.js  38.1 KiB             9  [emitted]  

This is my route definition:

export default [{
    path: '/user',
    component: Layout2,
    children: [
        {
            path: '/',
            name: 'user',
            component: () => /* webpackChunkName: "view-[request]" */ import('@/components/user'),
        },
    ]
}]

And this is my Webpack config:

/**
 * As our first step, we'll pull in the user's webpack.mix.js
 * file. Based on what the user requests in that file,
 * a generic config object will be constructed for us.
 */
let mix = require('laravel-mix/src/index');

let ComponentFactory = require('laravel-mix/src/components/ComponentFactory');

new ComponentFactory().installAll();

require(Mix.paths.mix());

/**
 * Just in case the user needs to hook into this point
 * in the build process, we'll make an announcement.
 */

Mix.dispatch('init', Mix);

/**
 * Now that we know which build tasks are required by the
 * user, we can dynamically create a configuration object
 * for Webpack. And that's all there is to it. Simple!
 */

let WebpackConfig = require('laravel-mix/src/builder/WebpackConfig');

const config = new WebpackConfig().build();

// Inject sass-loader options
config.module.rules
.filter(rule => rule.test.test && (rule.test.test('.sass') || rule.test.test('.scss')))
.forEach(rule => {
    const sassLoader = rule.loaders.find(loader => loader.loader === 'sass-loader');

    if (sassLoader) {
        Object.assign(sassLoader.options, {
            precision: 5,
            implementation: require('node-sass')
        });
    }
});

// Fix Hot Module Replacement bug
if (Mix.isUsing('hmr')) {
    // Remove leading '/' from entry keys
    config.entry = Object.keys(config.entry)
    .reduce((entries, entry) => {
        entries[entry.replace(/^\//, '')] = config.entry[entry];
        return entries;
    }, {});

    // Remove leading '/' from ExtractTextPlugin instances
    config.plugins
    .forEach((plugin) => {
        if (plugin.constructor.name === 'ExtractTextPlugin') {
            plugin.filename = plugin.filename.replace(/^\//, '');
        }
    });
}



module.exports = config;

Now I am wondering why all the files are named 0.js etc. and not like the webpackChunkName.

Additionally I'd like to use cache-busting on the chunks as they are always cached by my browser, so if I re-run Webpack, I often need to clear my cache completely.

My questions are:

  • How can I make use of the WebpackChunkName correctly?
  • How can I prevent caching of the chunks?
May
06
5 months ago
Activity icon

Replied to Missing Parameter For Vue-router When Using BeforeRouteEnter

Hi @bobbybouwmann

first of all: Thanks for your reply.

I am using vuex to store the data of the logged-in user. The user the edit link is placed for is a user the authenticated user is managing.

Activity icon

Started a new Conversation Missing Parameter For Vue-router When Using BeforeRouteEnter

Hello everybody,

I am using the vue-router to navigate through my SPA.

This is my router:

export default [{
    path: '/user',
    component: Layout2,
    meta: {
        requiresAuth: true
    },
    children: [
        {
            path: '/',
            name: 'user',
            component: () => /* webpackChunkName: "view-[request]" */ import('@/components/Index'),
            meta: {
                requiresAuth: true
            },
        },
        {
            path: ':id',
            name: 'user.view',
            component: () => /* webpackChunkName: "view-[request]" */ import('@/components/View'),
            meta: {
                requiresAuth: true
            },
        },
        {
            path: ':id/edit',
            name: 'user.edit',
            component: () => /* webpackChunkName: "view-[request]" */ import('@/components/Edit'),
            meta: {
                requiresAuth: true
            },
        },
    ]
}]

Now I added this:

<b-btn variant="primary" size="sm" :to="{ name: 'user.edit', params: { id: user.id }}">Edit</b-btn>

It's a part of vue-bootstrap.

I also make use of beforeRouteEnter:

data: () => ({
        user: {},
    }),
    beforeRouteEnter (to, _from, next) {
        axios
        .get ('/api/user/' + to.params.id).then ((resp) => {
            next ((vm) => {
                vm.user = resp.data.data;
            });
        });
    },

Alright - this seems to work - but I am receiving this warning:

[vue-router] missing param for named route "user.edit": Expected "id" to be defined

If I dump user.id in my component, 1 is being returned.

So now I am wondering: The component shouldn't be rendered if beforeRouteEnter is not finished, right? But why do I get this warning?

Apr
29
5 months ago
Activity icon

Replied to Using Vue To Authenticate With Laravel/passport?

I had a look at this project: https://github.com/andranikbadalyan/Laravel-Passport-Vue-Auth/tree/c92b3f5df210c46a271b9a93e45f7c3fa86a3209

You can use this to set up auth with passport. I did it and it works (for now ;-) )

Apr
27
5 months ago
Activity icon

Started a new Conversation Using Vue To Authenticate With Laravel/passport?

Hello,

I would like to create my first SPA; I am using vue-router and vuex to handle routes and states.

Now I'd like to use laravel/passport with Vue to authenticate, but to be honest: I only find tutorials with using tymondesigns/jwt-auth.

So my question is: Are there good docs for user login/logout with Passport? Thank you very much!

Apr
24
5 months ago
Activity icon

Replied to Alias For Model?

Ok, so I misunderstood your post. Thank you very much 😊