ahoi

ahoi

Member Since 11 Months Ago

Experience Points 3,370
Experience Level 1

1,630 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.

14 Aug
1 week ago

ahoi 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?

12 Aug
1 week ago

ahoi left a reply on 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?

ahoi left a reply on 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?

ahoi left a reply on 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.

ahoi left a reply on 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.

11 Aug
1 week ago

ahoi 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?

05 Aug
2 weeks ago

ahoi left a reply on Creating-Observer Does Not Save Modifications?

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

ahoi 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();

?

31 Jul
3 weeks ago

ahoi 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.

15 Jul
1 month ago

ahoi left a reply on 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;
                    }
                });
            }
        }

ahoi left a reply on 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?

ahoi left a reply on 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 :-)

ahoi 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

ahoi left a reply on 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');
    }

ahoi left a reply on "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 :-)

11 Jul
1 month ago

ahoi 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.

03 Jul
1 month ago

ahoi 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 ;-) )

ahoi left a reply on 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 :-)

02 Jul
1 month ago

ahoi 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.

19 Jun
2 months ago

ahoi left a reply on 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 :-)

17 Jun
2 months ago

ahoi 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?

16 Jun
2 months ago

ahoi 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?
14 Jun
2 months ago

ahoi 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 :-)

08 Jun
2 months ago

ahoi 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 :-)

30 May
2 months ago

ahoi left a reply on 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!

ahoi 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?

29 May
2 months ago

ahoi left a reply on 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.

ahoi 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 :-)

14 May
3 months ago

ahoi 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?
06 May
3 months ago

ahoi left a reply on 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.

ahoi 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?

29 Apr
3 months ago

ahoi left a reply on 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 ;-) )

27 Apr
3 months ago

ahoi 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!

24 Apr
3 months ago

ahoi left a reply on Alias For Model?

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

ahoi left a reply on Alias For Model?

Hi @snapey ,

I'm sorry, I didn't make myself clear.

I referred to your blog and its profile types AdminProfile and CustomerProfile.

It would be great if a user could have both types. A third profile type would not be necessary, would it? But at the moment I can't manage that a user can have both profile types.

Thanks again in advance :-)

ahoi left a reply on Alias For Model?

Hi @snapey

Your answer fits my needs. But I got another question: Would it be possible somehow that a User can have both user profile types?

So a User could be an AdminUser and a Customer the same time.

I tinkered around with morphMany but there I only got it working if the profiles have the same class.

15 Apr
4 months ago

ahoi started a new conversation Watch Array For Changes And Prevent Items To Be Empty

Hello everybody,

I got an array of objects like this:

item.list:

[
  {
    price: 1,
    factor: 1
  },
  {
    price: 1,
    factor: 2
  },
]

Now I would like to create a watcher, that prevents price or factor to be empty. If it is, it automatically should be set to 0.

I would do it like this:

'item.list': {
    handler: function (val, oldVal) {

        //how to get the key of the changed object here? 
    },
    deep: true
}

But unfortunately I don't get the key of the changed element?

12 Apr
4 months ago

ahoi left a reply on Alias For Model?

Hi @snapey

That's what I would love to do... But how can I make sure that only users having the "customers" role are linked to that model?

11 Apr
4 months ago

ahoi started a new conversation Alias For Model?

Hello everybody,

I got a Model called User. Each user can have an id, name, email, role etc.

Now I would like to create a model that is called Customer, which allows a customer to log in. But a Customer should always be a User with the role customer.

Is it possible to create an alias that defines a Customer to be a User that has a specific role assigned like this:

$customer->assignRole('customers');
09 Apr
4 months ago

ahoi started a new conversation Update Model With Dynamic HasMany-relation

Hello everybody,

I got a model that is called Car. This Car hasMany Attributes.

An attribute looks like this:

id = int
car_id = int
description = text

Now I can create a new Car and assign many Attributes. If I update the Car, I also would like to update the Attributes.

This is how I'd do this at the moment:

public function update(Request $request)
{
    /*Get car*/
    $car = Car::findOrFail($request->car_id);
    
    /*Get car attributes and delete them*/
    $car->attributes->each(function ($attribute) {
        $attribute->delete();
    });
    
    /*Save new attributes*/
    $attributes = $request->input('data.attributes');
    
    foreach ($attributes as $attribute) {
        Attribute::create([
            'car_id'      => $car->id,
            'description' => $attribute['description'],
        ]);
    }
    
    /*Update car title*/
    $car->title = $request->input('data.title');
    $car->save();
    
    return response()->json(['message' => 'success']);
}

So first of all I'd delete all attributes and recreate them afterwards according to the input. Is there any room for improvements here? How would you update these dynamic fields?

27 Mar
4 months ago

ahoi started a new conversation Add Object To An Array And Modify It Without Modifying The Initial Object

Hello everybody,

I created a little codepen to demonstrate my issue: https://codepen.io/spqrinc/pen/moYKZo

If you add "hello" from the select field multiple times, there will be text input fields where you can edit the value of this specific element. Well: That's the plan.

But if you change the title of one "hello" field, all other entries are getting a new title, too. How can I prevent this? I would like to have this new title only on the specific entry.

This is my source:

new Vue({
    el: '#app',
    data: {
        items: [
            {title: 'hello'},
            {title: 'world'}
        ],
        itemlist: [],
        newItem: {}
    },
    methods: {
        addItem: function (option) {
            this.itemlist.push (this.newItem);
        },
    },
});
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<div id="app">
    <select v-model="newItem">
        <option v-for="item in items"
                :value="item">{{item.title}}
        </option>
    </select>
    <button v-on:click="addItem">Add</button>
    <div v-for="item in itemlist">
        <input v-model="item.title"/>
    </div>
</div>
</body>
</html>
16 Mar
5 months ago

ahoi started a new conversation 70GB Of Logs (Laravel.log) Because Of Failing Job?

Hi there,

today, my queue worker wrote round about 70GB of logs (laravel.log). It was always the same message:

[2019-03-16 21:09:07] local.ERROR: include(/var/www/example.org/example/vendor/composer/../laravel/framework/src/Illuminate/Queue/FailingJob.php): failed to open stream: No such file or directory {"exception":"[object] (ErrorException(code: 0): include(/var/www/example.org/example/vendor/composer/../laravel/framework/src/Illuminate/Queue/FailingJob.php): failed to open stream: No such file or directory at /var/www/example.org/example/vendor/composer/ClassLoader.php:444)
[stacktrace]
#0 /var/www/example.org/example/vendor/composer/ClassLoader.php(444): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'include(/var/ww...', '/var/www/exampl...', 444, Array)
#1 /var/www/example.org/example/vendor/composer/ClassLoader.php(444): include()
#2 /var/www/example.org/example/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/var/www/exampl...')
#3 [internal function]: Composer\Autoload\ClassLoader->loadClass('Illuminate\\Queu...')
#4 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(440): spl_autoload_call('Illuminate\\Queu...')
#5 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(426): Illuminate\Queue\Worker->failJob('redis', Object(Illuminate\Queue\Jobs\RedisJob), Object(ErrorException))
#6 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(358): Illuminate\Queue\Worker->markJobAsFailedIfWillExceedMaxAttempts('redis', Object(Illuminate\Queue\Jobs\RedisJob), 3, Object(ErrorException))
#7 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(331): Illuminate\Queue\Worker->handleJobException('redis', Object(Illuminate\Queue\Jobs\RedisJob), Object(Illuminate\Queue\WorkerOptions), Object(ErrorException))
#8 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(277): Illuminate\Queue\Worker->process('redis', Object(Illuminate\Queue\Jobs\RedisJob), Object(Illuminate\Queue\WorkerOptions))
#9 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(118): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\RedisJob), 'redis', Object(Illuminate\Queue\WorkerOptions))
#10 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(102): Illuminate\Queue\Worker->daemon('redis', 'default', Object(Illuminate\Queue\WorkerOptions))
#11 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(86): Illuminate\Queue\Console\WorkCommand->runWorker('redis', 'default')
#12 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#13 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#14 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#15 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#16 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Container/Container.php(572): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#17 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
#18 /var/www/example.org/example/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#19 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#20 /var/www/example.org/example/vendor/symfony/console/Application.php(901): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#21 /var/www/example.org/example/vendor/symfony/console/Application.php(262): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#22 /var/www/example.org/example/vendor/symfony/console/Application.php(145): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#23 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Console/Application.php(89): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#24 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#25 /var/www/example.org/example/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#26 {main}
"} 

Is it correct that a specific file could not be found by ClassLoader or don't I understand that correctly?

I just did a composer dump-autoload...

03 Mar
5 months ago

ahoi left a reply on Modify Array Before Saving It

This helps a lot! Thank you very much!

02 Mar
5 months ago

ahoi started a new conversation Modify Array Before Saving It

Hello everybody,

I am using a JSON field in my database. Now, I am saving an Array in it that is converted to JSON before:

User model

 protected $casts
        = [
            'options' => 'array',
        ];

Saving an option

$options = $user->options;                                                                                                                                                                       $options['notify'] = true;                                                                                                                                                               $user->options = $options;                                                                                                                                                                       $user->save();    

Now the Array comes from an user form input, this is validated as array.

Is it possible to modify this array before saving to make sure that it contains at least the field notify? If the array does not contain thenotify field, create one with value false.

I thought I could use something like this:

    public function setOptionsAttribute($value)
    {
        $this->attributes['options'] = json_encode($value); //TODO: Check for correct entries, ...
    }

Is this the suggested way?

Another question: On saving, does

            'options'              => 'array',

prevent my app from SQL-injection attacks or do I have to manually check the input?

ahoi left a reply on JSON In API Resource Is Quoted?

Hm, that's strange...

In my browser (app) the JSON user.options looks like this:

{"notify_on_mail":true}

But if I try to access user.options.notify_on_mail I am getting undefined. I also renamed notify_on_mail to notify, without success.

01 Mar
5 months ago

ahoi started a new conversation JSON In API Resource Is Quoted?

Hi everybody,

I my API Resource I am accessing $user->options, which is a JSON field:

        Schema::table('users', function (Blueprint $table) {
            $table->json('options');
        });
<?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,
            'options' => $this->options,
        
        ];
    }
}

Now my result (seen on my browser's network console) is this:

options: "{\"notify_on_mail\":true}"

How can I return this unquoted?

The problem: I can not access this in Vue.js:

undefined is not an object (evaluating '_vm.user.options.notify_on_mail')

Your help is highly appreciated :-)

20 Feb
6 months ago

ahoi started a new conversation Get ID Of Created Element In Observer

Hey there,

I am using an observer (https://laravel.com/docs/5.7/eloquent#observers) to create a App\Team, once a App\Group is created:

    public function created(Group $group)
    {
        if (request()->has('data.name')) {
            Team::create([
                'name'       => $company->name,
                'owner_id'   => request()->user()->getKey(),
                'group_id'   => $group->id,
            ]);
            
            request()->user()->attachTeam($team);

            $group->team_id = $team->id;
            $group->save();
        }
    }

Unfortunately

'group_id'   => $group->id,

is always saving null, as $group->id is empty. I thought the created event fires after the entry is created? At this moment it should already have an ID?

I am very happy for every hint you can give me :-)

10 Feb
6 months ago

ahoi started a new conversation Axios.get(): Not Allowed By Access-Control-Allow-Headers.

Hello everybody,

at the moment, I am trying to use axios to send a little GET request:

axios.get (process.env.MIX_MATOMO_URL + '/index.php?module=API&method=AjaxOptOut.isTracked&format=json').then ((response) => {
                this.tracked = response.value;
});

This fails with:

Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.

Alright - I added my domain to Matomo's cors_domains - but without success.

Any help is highly appreciated :-)

ahoi started a new conversation Send Verification Mail On Socialite Login

Hello everybody,

actually I am using MustVerifyEmail on user's registration:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Scout\Searchable;


class User extends Authenticatable
    implements MustVerifyEmail
{
    use Notifiable,  Searchable;
}
    

Now I am additionally using Laravel Scout to login using Facebook and Twitter.

I created a login controller and added this:

function findOrCreateUser($providerUser, $provider)
{
    
    $user = User::create([
        'email'     => $providerUser->getEmail(),
        'lastname'  => $providerUser->user['last_name'],
        'firstname' => $providerUser->user['first_name'],
    ]);
    
    
    event(new Registered($user));    
    
    return $user;
}

Now I am triggering this event manually: event(new Registered($user)); to send the verification mail. I am just wondering: Is there a more elegant way to archive this?