sirhxalot

sirhxalot

Member Since 3 Years Ago

Zurich

Experience Points 38,870
Experience Level 8

1,130 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 351
Lessons
Completed
Best Reply Awards 4
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.

06 Jun
1 month ago

sirhxalot left a reply on Nested Resource Controllers

The only remaining idea I have is to clear the cache: php artisan cache:clear otherwise I will need to play with your code.

sirhxalot left a reply on Nested Resource Controllers

And its still not working? Thats strange:

If a matching model instance is not found in the database, a 404 HTTP response will be automatically generated.

Is there a possibility that you share your code on github?

sirhxalot left a reply on Nested Resource Controllers

@CTYLER - Is your class within the namespace App? And is there a id column within your migration?

sirhxalot left a reply on Nested Resource Controllers

@CTYLER - It would be a problem if you didn't set the table attribute within your model.

Please add the following to your model:

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'course_categories';

sirhxalot left a reply on Nested Resource Controllers

@CTYLER - Hi @ctyler.

If have updated my comment.

sirhxalot left a reply on Nested Resource Controllers

Hi @ctyler

The retuning value is your eloquent model so you already done it? Checkout the id attribute within dd to see the id.

05 Jun
1 month ago

sirhxalot left a reply on How To Pass Only Form Data Not The Html From One Component To Another On Submit

Hi @saurabh.kackar!

I am not sure if I understand your request - where do you stuck?

If I interpret your title you are looking propably for FormData: https://developer.mozilla.org/de/docs/Web/API/FormData

If you dont know how to pass data in please checkout events: https://vuejs.org/v2/guide/events.html or properties: https://vuejs.org/v2/guide/components-props.html.

And if you are not sure how to post data to a route checkout axios: https://github.com/axios/axios.

Hope I could help you.

sirhxalot left a reply on Laravel Dusk - SweetAlert - AssertDialog

From Dusk till dawn - @bobbybouwmann is there for us!

Thank you again you are right!

My final assertion looks like the following:

        $this->browse(function (Browser $browser) use ($user) {
            $browser->loginAs($user)
                    ->visit('/order/create')
                    ->assertDontSee("An error occurred we couldn't proceed. Please checkout your form inputs.")
                    ->type('@first_name', '')
                    ->press('.preview-button')
                    ->waitFor('.swal-overlay--show-modal')
                    ->assertSee("An error occurred we couldn't proceed. Please checkout your form inputs.")
                    ->logout();
        })

It asserts that the text will only be seen if the modal is shown - I am happy ;)

It was my first attemp that a sweet alert is not a dialog - but I was hoping since the role="dialog" attribute has been set that it can detect as a dialog - I was wrong.

I am little bit confused whats a dialog than?

Am I correct that the following elements are dialogs? Are there any more?

Thanks again and keep on going.

04 Jun
1 month ago

sirhxalot started a new conversation Laravel Dusk - SweetAlert - AssertDialog

Hi Folks!

I would like to write a Laravel Dusk Test in Laravel 5.8 in order to test dialogs.

So far I have made a Vue Component that contains a button. When the button is clicked it sends a post request to a controller method. If we had a failure e.g. invalid input (validation) a 422 stauts code will be thrown and a sweet alert modal pop ups.

Everything is working as expected. However I wanted to create a Dusk test to check if the modal has been opened so I tried:

        $this->browse(function (Browser $browser) use ($user) {
            $browser->driver->manage()->deleteAllCookies();
            $browser->loginAs($user)
                    ->visit('/order/create')
                    ->type('@first_name', '')
                    ->press('.preview-button')
                    ->waitForDialog(1)
                    ->assertDialogOpened("An error occurred we couldn't proceed. Please checkout your form inputs.")
                    ->logout();
        });

The test seems to be fine since the modal will be opened. However it respond with: Facebook\WebDriver\Exception\TimeOutException: Waited 1 seconds for dialog.

When I open the screenshot in Browser/screenshots/ I see the message!

Besides the deleteAllCookies() has been added just for testing purposes it works neither with or without the code.

Does somebody has a clue?

Thank you in advance.

22 May
1 month ago

sirhxalot left a reply on Laravel Authentication Using Form Request Instead Of Array Validation.

@FTIERSCH - ? You are right this will improve the code.

This was because I was not being able to see the forest for the trees!

In a perfect world it would be cool to remove the validator method.

However the solution is good enough for me.

Thank you @

sirhxalot started a new conversation Laravel Authentication Using Form Request Instead Of Array Validation.

Hi Folks!

I am using Laravel 5.8 and enabled the authentication php artisan make:aut. Everything is working as expected.

But when dealing with user informations that will be stored within the register route I would be also able to reuse the validation for other requests e.g. if I would like to update the data (we call it profile storage for simplicity ;))

So a form request seems to be the solution and I have done it:

App\Http\Requests\StoreUser.php:

    public function rules()
    {
        return [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name'  => ['required', 'string', 'max:255'],
            'title'      => ['max:255'],
            'function'   => ['max:255'],
            'phone'      => ['max:255'],
            'mobile'     => ['max:255'],
            'location'   => ['required', 'exists:locations,id'],
            'email'      => ['required', 'email', 'string', 'max:255'],
            'password'   => ['required', 'string', 'min:8', 'max:255', 'confirmed'],
        ];
    }

But how can I use the form request within the registration controller (App\Http\Controllers\Auth\RegisterController)?

It seems that I can't remove the validator method? I also could not pass in the Form Request instead of an array? And even the create method doesn't allow this!

So my first attemp was to use the rules within the methods:

 /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        $formRequestRules = app(StoreUser::class)->rules();

        return Validator::make($data, [
                'first_name' => $formRequestRules['first_name'],
                'last_name'  => $formRequestRules['last_name'],
                'title'      => $formRequestRules['title'],
                'function'   => $formRequestRules['function'],
                'phone'      => $formRequestRules['phone'],
                'mobile'     => $formRequestRules['mobile'],
                'location'   => $formRequestRules['location'],
                'email'      => $formRequestRules['email'],
                'password'   => $formRequestRules['password'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        $user = User::create([
            'first_name'     => $data['first_name'],
            'last_name'      => $data['last_name'],
            'academic_title' => $data['title'],
            'function'       => $data['function'],
            'phone'          => $data['phone'],
            'mobile'         => $data['mobile'],
            'location_id'    => $data['location'],
            'email'          => $data['email'],
            'password'       => Hash::make($data['password']),
        ]);

        $user->assignRole('customer');

        return $user;
    }

It works but I am not a fan!

Is there a better solution where I can use one method to validate and store the user?

Thank you in advance for any possible solutions.

Cheerio!

sirhxalot left a reply on Check If Element Has Attribute With Laravel Dusk

Hey @bobbybouwmann

Thank you so much for your hint - it worked out as expected.

The final assertion looks like this:

$browser->assertSourceHas('<input name="email" dusk="email" id="i-email" type="email" maxlength="255" value="[email protected]" required="required" readonly="readonly" class="input ">');

What a mess!

I am not happy with this solution since it doesn't subscribe what I am expecting.

In a perfect world I would like to have something like the following:

$browser->assertHasAttribute($field, $expectedAttribute);

If I have time I maybe going to open issue (enhancement request) for this.

Anyhow: Bedankt!

sirhxalot left a reply on Auth::user() Returns Null Using Custom Login

@adrock I thought so? I am glad you made it work it out!

Just to improve this you may extract it to the authenticated method as described here: https://laravel.com/docs/5.8/authentication#authenticating-users

21 May
1 month ago

sirhxalot left a reply on Auth::user() Returns Null Using Custom Login

If you call the login and removed all dd's i dont see why it should not workout I will test this asap. But for now I have to leave you there.

sirhxalot left a reply on Auth::user() Returns Null Using Custom Login

And you call the login (/login)? Correct

sirhxalot left a reply on Auth::user() Returns Null Using Custom Login

And if you dd the user object its an instance off app/user? Than remove the dd and you should be logged in?

sirhxalot left a reply on Auth::user() Returns Null Using Custom Login

All what it does in the turial is to fetch a user using a where statement. Give the user object to login and you should be done?

sirhxalot left a reply on Auth::user() Returns Null Using Custom Login

If your code looks like the posted one I dont get it the tutorials code is different?

sirhxalot left a reply on Auth::user() Returns Null Using Custom Login

Regarding to dd() method causes null on authentication:

This should be expected - dd means die and dump.

sirhxalot left a reply on Auth::user() Returns Null Using Custom Login

Allrigthy you just want to change the useres identifier.

I have not tested what is written within the article - but the instructions seems to be correct!

Your posted code looks slightly different?

sirhxalot left a reply on Auth::user() Returns Null Using Custom Login

Hi @adrock

I am not sure how you made your custom login?

My guess is that there is your own authentication service provider? So you may register the provider and its guards: https://laravel.com/docs/5.8/authentication#adding-custom-user-providers

But it seems like an issue with the guards - please checkout: https://laravel.com/docs/5.8/authentication#adding-custom-guards

Greetings Sirthxalot

sirhxalot started a new conversation Check If Element Has Attribute With Laravel Dusk

Hi Folks!

I am using Laravel 5.8 in combination with Laravel Dusk.

How can I check if an element has an attribute?

For example I would like to check if an input field has the readonly attribute or not.

I have tried to use assertSee but it does not work?

I double checked if the attribute isset in the HTML code using a pause and opened the console - its there!?

This is the HTML rendered by Laravel:

<section id="email-form-section" class="field" wfd-id="32"><label for="i-email" class="label " wfd-id="37"><span wfd-id="39">E-Mail Address</span> <span class="is-mandatory" wfd-id="38">*</span></label> <div class="columns is-multiline is-vcentered" style="margin-bottom: 0px;" wfd-id="33"><div class="column" wfd-id="34"><div class="control has-icons-left" wfd-id="35">

<input name="email" dusk="email" id="i-email" type="email" maxlength="255" value="[email protected]" required="required" readonly="readonly" class="input " wfd-id="115">

 <span class="icon is-small is-left" wfd-id="36"><i class="far fa-envelope"></i></span></div></div></div></section>

And this is the test case related to this issue:

namespace Tests\Browser;

use App\User;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Spatie\Permission\Traits\HasRoles;
use Symfony\Component\Debug\Tests\Fixtures\TraitWithInternalMethod;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class ProfileTest extends DuskTestCase
{
    use DatabaseMigrations;

    /** @test */
    public function its_profile_form_is_up()
    {
        $user = factory('App\User')->create([
            'first_name' => "Aegon",
            'last_name' => "Tagaryen",
            'academic_title' => "King",
            'function' => "Torture",
            'phone' => "+414444444",
            'mobile' => "+41788888888",
            'location_id' => 1,
            'email' => "[email protected]",
            'password' => bcrypt('secret')
        ]);

        $this->browse(function (Browser $browser) use ($user) {
            $browser->loginAs($user)
                    ->visit('/profile')
                    ->assertValue('@first_name', 'Aegon');

            $browser->with('@email', function ($emailInput) {
                $emailInput->assertSee('readonly');
            });
        });
    }
}

And finaly the console output:

Time: 21.51 seconds, Memory: 26.00 MB

There was 1 failure:

1) Tests\Browser\ProfileTest::its_profile_form_is_up
Did not see expected text [readonly] within element [body [dusk="email"]].
Failed asserting that false is true.

I have tried to use another selector e.g. #i-email but it didn't worked out.

Does somebody have an idea what I do wrong?

04 Apr
3 months ago

sirhxalot left a reply on How To Hide And Display Table

Would you please change the threads channel from ~~Laravel~~ to Tips?

In my opinion this thread has nothing to do with Laravel.

Thank you in advance.

sirhxalot left a reply on How To Hide And Display Table

Hey @sparkyltu !

The problem when using visibility hidden is that the element stays within your content flow (same size, etc.) while it's simply invisible.

In order to avoid any spaces within the viewport you can use display:none but you propably need to switch to display:table when showing the table again. Unfortunaly I don't understand what you mean by the table is getting distorted?

27 Apr
1 year ago

sirhxalot left a reply on Use All() Method Or Get() To Fetch All Entries?

Hi folks!

First of all thank you all for your replies. I figured out what made me so confused. Please take a shot at the image below:

?

No not that one - that's me. The next one:

I used something that doesnt exist to query

Somehow I used Eloquent with a non existing get() method instead of all()which let me think that Eloquent was about 3x times slower (thanks @snapey to correct me - my statement is nonsense).

And thank you also @alielkhateeb which perfectly described when to use all() and when to use get().

26 Apr
1 year ago

sirhxalot left a reply on Update A Float Column Value Results Rounding Off

Yes @Cronix is right.

Whenever is possible try to store integer values.

But I disagree with the decimal type - would be the same issue like floats and doubles.

Here you will find explainations: https://stackoverflow.com/questions/48516430/laravel-or-php-mysql-cuts-float-numbers-after-decimal-point.

sirhxalot left a reply on Update A Float Column Value Results Rounding Off

Hi @THAMEERA!

How does your migration file look like?

Are you using $table->float('amount', 8, 2);?

sirhxalot left a reply on Use All() Method Or Get() To Fetch All Entries?

Because I would expect that for example the Eloquent solution maybe loading mutators and observers or other Eloquent related stuff where the Query Builder wouldn't -

BUT THAT's NOT THE CASE!!!

sirhxalot left a reply on Use All() Method Or Get() To Fetch All Entries?

Yea I did. And maybe I missunderstanding something.

My intepretation how all() works:

  1. A new Eloquent Model will be instanciated
  2. The Query Builder will be attached to the model (but why not use the Query Builder directly?)
  3. The get() method will be triggered fetching all [*] rows

But why does this takes longer? Answer: Eloquent Model - Right?

Do I ever have a benefit from using Eloquent? Because I just see two downpoints:

  • slower
  • query can not be modified

Hope you can follow appreciate your quick response by the way.

sirhxalot left a reply on Use All() Method Or Get() To Fetch All Entries?

Thanks @stefanbauer!

Do you know where I can found more background information what is going on with this topic - Why is Eloquent that slow? Is it because of traits? And is there really no benefit?

I am just curios and it wont let me alone ;)

sirhxalot started a new conversation Use All() Method Or Get() To Fetch All Entries?

Hi folks!

I have heard that the get() method (from Query Builder) is much more performant than the all() method from Eloquent Model is. So I tried to this out and indeed the Query Builder solution is much more faster.

So my first thought was there must be a benefit when I use the Eloquent solution - since its more than 3x times slower than the Query Builder. But I didn't find any benefit to use the all() method.

As far as I heard there are some traits and other stuff that will be used for the Eloquent Model, but is there any benefit? I didn't found anything even mutators are working exact the same.

Why should I ever use User::all() to fetch all entries, when User::get() is much faster?

Best regards Alexander Bösch - sirthxalot

12 Jan
1 year ago

sirhxalot left a reply on Logging In Two Computers At The Same Time?

Hi @danaia!

I am not pretty sure what you mean with network become awake? The technologie you are looking for is web socket: https://www.html5rocks.com/de/tutorials/websockets/basics/

Laravel has an implrmentation in order to broadcast well at least messages: https://laravel.com/docs/5.5/broadcasting

Hope this give you a hint.

sirhxalot left a reply on Guidence On How To Deploy My Laravel Websites.

Hi @kaizenKid!

@topvillas is recommending digital ocean: https://www.digitalocean.com.

I am using this service as well and it works great! But maybe it is a liitle overwhelmed for beginners. Anyhow there is a guidance how to deploy your app: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-laravel-application-with-nginx-on-ubuntu-16-04

Honestly I have never read it before but when I flew over the article it seems to be mention everything needed to deploy Laravel.

Hope this helps.

sirhxalot left a reply on Dependency Issues

Hey @JPERKS!

You try to install Laravel 4.2 and the most of the packages you try to install are not compatible with this version. As an example Tinker requires at least 5.1. The PHP7 is comming from one of those dependecies which are not compatible with Laravel 4.2.

sirhxalot left a reply on Send Data To Vue Component From Blade Template File

Hey @qbixx!

I usually prefer option 2. There are many ways how to set a JavaScript variable from PHP. Usually I add an extension for this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer.

It allows to add JavaScript Variables from the controller.

So you can create a JavaScript Module and use these variables directly within it.

Another way is if you take a look at the authentication layout master file, after php artisan make:auth command. You will see <meta name="csrf-token" content="{{ csrf_token() }}"> and within your resources/assets/js/bootstrap.jsyou will see the followinglet token = document.head.querySelector('meta[name="csrf-token"]');`.

Like I already said I prefer the package from Jeffrey.

Hope this helps!

10 Aug
1 year ago

sirhxalot left a reply on Algolia Custom Filter For Index With Relationships. (Scout)

I ran into an error due database seeding since user wasn't available so I needed to tweak in. This is my final solution:

    public function toSearchableArray()
    {
        if ($this->user && $this->user->hasRole('client')):
            return $this->toArray();
        endif;
    }

sirhxalot left a reply on Algolia Index With Nested Relationships (incl. HasMany)

Yes there is a better solution I have added the following to my user:

    public function hasRole($role)
    {
        $roles = $this->roles->toArray();
        $roles = array_column($roles, 'name');
        return in_array($role, $roles);
    }

Now I am able to check it like so:

    public function toSearchableArray()
    {
        $this->user->roles;
        if ($this->user->hasRole('client')):
            return $this->toArray();
        endif;
    }

It works at least. But is there even a better way to solve this?

sirhxalot left a reply on Algolia Index With Nested Relationships (incl. HasMany)

Okay I get it.

First of all one mistake which is very hard for you to find out is that my relationship between a user and its roles was roles instead of role.

Finally I am not sure if this is the best solution but it works for now:

    public function toSearchableArray()
    {
        $this->user->roles;
        if ($this->user->roles->first()->name == 'client'):
            return $this->toArray();
        endif;
    }

May somebody has a better idea to handle this. The first thing which pokes into my head is that I will need to get the first roles name to check. Luckly it's the case that the user will first get the client assignment but what if somebody is mutating and will be client later than this doesn't work. Do you have a solution for this?

sirhxalot left a reply on Insert/Update Throws Validator Exception

Hi Maedler

it seems that you will have an issue by resolving something out of the IOC container: Call to a member function make() on null. May this service isn't registered within Lumen? Or checkout if you need a facade than unncomment: https://github.com/laravel/lumen/blob/master/bootstrap/app.php#L26.

Hope it helps.

sirhxalot started a new conversation Algolia Index With Nested Relationships (incl. HasMany)

Hi Folks!

I would like to create an Algolia index with some conditions, but let me first show you my structure I have so far:

  1. Table users In this table I will store all my users.
  2. Table persons This is where personal information about the user will be stored, e.g. first name, gender and so on. And it is the table I would like to index. A person can have one user. Furthermore a User can have many roles. Person > User (One to One). User > Role (Has Many)
  3. Table role This is where I will store the available roles for users: client, administrator and owner
  4. Table role_user This is where I determine the relationship between a user and its roles.

Allrighty hope anything is clear so far. I have a user with its person (or profile) and a user can have as many roles as he wants to.

I will use scout and algolia to create my search feature. So when I would like to publish the indexes I will run: php artisan scout:import "App\Person". And it works.

But I would like to only publish persons who has a user with the role of client. And I don't know how to query it correctly. I am trying to change the toSearchableArray method but can't get the roles? So far I have tried things like:

    public function toSearchableArray()
    {
        $this->with('user.role');
        return $this->toArray();
    }

    // or ...

    public function toSearchableArray()
    {
        $this->user->role;
        return $this->toArray();
    }

Anything without success. And I still don't now how to filter than down to the role client. So may you please help me with this since I am kind of lost.

Thank you in advance and best regards Sirthxalot

30 May
2 years ago

sirhxalot left a reply on Why My Custom Package Class Just Works If I Add It Into The Root Composer.json?

  1. You need to change the privacy of your GitHub repository to public.
  2. Visit: https://packagist.org/ and create an account.
  3. After login to packagist go to: https://packagist.org/packages/submit
  4. Paste in the URL to your repository and click submit.
  5. Your repository is now downloadable using: composer install ihaveforgotthename

You than don't need to add the autoloading within your Laravel application, Composer will do that for.

But be aware anybody will have access to your repository and can download or install it with Composer.

sirhxalot left a reply on Why My Custom Package Class Just Works If I Add It Into The Root Composer.json?

Ahh okay yes this looks like our solution but I didn't set it up my collegue did. I will ask him if has a good day but this is all I can do for you. hope it helped?

sirhxalot left a reply on Why My Custom Package Class Just Works If I Add It Into The Root Composer.json?

And this is where all the public repositories are located at: https://packagist.org/

You only need to change the privacy if you want.

sirhxalot left a reply on Why My Custom Package Class Just Works If I Add It Into The Root Composer.json?

No but if your company doesn't have a solution for this like: https://packagist.com/, than it will may not work out.

Please take a look at: https://getcomposer.org/doc/articles/handling-private-packages-with-satis.md

sirhxalot left a reply on Why My Custom Package Class Just Works If I Add It Into The Root Composer.json?

Ahh now I see you have made a private package - is this necessary?