devk

devk

Member Since 2 Years Ago

Experience Points 10,880
Experience Level 3

4,120 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 52
Lessons
Completed
Best Reply Awards 7
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

24 May
2 days ago

devk left a reply on $this->mock(..) Doesn't Mock The Interface In The Controller I'm Calling

Damn, my bad. I had an alias and was referring to the wrong interface name.

All is good and it works as expected

devk left a reply on $this->mock(..) Doesn't Mock The Interface In The Controller I'm Calling

I tried that as well with the same results.

->mock(...) is just a shorthand for that (See docs)

devk started a new conversation $this->mock(..) Doesn't Mock The Interface In The Controller I'm Calling

Hi

trying to make this work:

$this->mock(ApiContract::class, function ($mock) {
    $mock
        ->shouldReceive('getStuff')
        ->once();
});

$response = $this
    ->actingAs($user)
    ->json('POST', '/get-stuff');

If I dd(app(ApiContract::class)); after the $this->mock(..), I get an instance of Mockery as I expect it to. But if I dd(app(ApiContract::class)); from within the controller that handles /get-stuff, I still get the actual implementation as defined in my service provider.

Any idea why?

19 May
1 week ago

devk left a reply on Different Output Files With Different Configs

Yeah that's what I ended up doing. Saw that mix uses let argv = require('yargs').argv; to get args passed in through package.json and ended up doing this:

mix
  .setPublicPath('./')
  .webpackConfig(sharedConfig);

if (argv.isserver) {
  mix
    .webpackConfig({
      externals: [nodeExternals()],
      node: {
        __dirname: false,
      },
    })
    .ts('node/server.tsx', './server.js');
} else {
  mix
    .copy('src/static', './public')
    .ts('src/ts/index.tsx', 'public/js/app.js');
}

Thanks!

18 May
1 week ago

devk left a reply on Different Output Files With Different Configs

As the next best thing is it possible to get node env variables within the webpack.mix.js?

Something like this would work well enough:

const sharedConfig = { // Shared config };

if (process.env.isserver) { mix .setPublicPath('./') .webpackConfig(sharedConfig) .copy('src/static', './public') .ts('src/ts/index.tsx', 'public/js/app.js'); } else { mix .setPublicPath('./') .webpackConfig({ ...sharedConfig, externals: [nodeExternals()], node: { __dirname: false, }, }) .ts('node/server.tsx', './server.js'); }

But I can't get this to work either.

devk started a new conversation Different Output Files With Different Configs

What's the best way to compile 2 JS files that require different configs? Namely, my server config requires some additional config options from my regular frontend config.

This is basically what I'm trying to do (spoiler, it doesn't work because the 2nd config is applied to the client side as well:

const sharedConfig = {
  // Shared config
};

mix
  .setPublicPath('./')
  .webpackConfig(sharedConfig)
  .copy('src/static', './public')
  .ts('src/ts/index.tsx', 'public/js/app.js');

mix
  .setPublicPath('./')
  .webpackConfig({
    ...sharedConfig,
    externals: [nodeExternals()],
    node: {
      __dirname: false,
    },
  })
  .ts('node/server.tsx', './server.js');
25 Mar
2 months ago
24 Mar
2 months ago

devk left a reply on Mockery `->with(SomeModel)` Returns Fails

Hmm no, they're not the same instance. The DB call happens in the service, any thoughts on how I should approach this?

Thanks for the explanation @s!

22 Mar
2 months ago

devk started a new conversation Mockery `->with(SomeModel)` Returns Fails

Hi,

I have a test like that :

$model = factory(SomeModel::class)->create()->fresh();

SomeService::shouldReceive('cancel')
    ->with($model)
    ->once();

and it always fails saying that passed in $model is not the same as the expected $model I've dumped them, compared attributes and they're the same. I've added ->fresh() to my factory to load the default attributes. I've also tried getting the $model with a new query $bet = Model::find($model->id);. The test always fails.

There are no changes made to the model before the cancel function in the SomeService.

Any help appreciated!

06 Mar
2 months ago

devk started a new conversation How To Scope BelongsTo Field To Only Return A Subset

Hi,

I have a categories table with parent_id that refers to the same table. For reference, the relationship will only have 2 levels (parent and children), but that doesn't matter for this question.

So in my Category Nova resource, I have something like this:

// ...
BelongsTo::make('Parent', 'parent', 'App\Nova\Category')
    ->sortable()
    ->nullable(),
// ...

Is it possible to scope the results of this to only parent relationships, basically adding this: ->whereNull('parent_id')?

I'm aware I can make a new relationship and add a scope there, but I would prefer to do it in the Nova resource as it wouldn't be used anywhere else in the project.

Thanks!

17 Jan
4 months ago

devk started a new conversation What's `->using(Pivot::class)` ?

I see there's a ->using(Pivot::class) method on the belongsToMany relationship, which supposedly sets the Pivot model to use in the relationship. What does that effect?

Thanks in advance!

01 Jan
4 months ago

devk left a reply on Polymorphic Relationship With 2 Different ID Columns

Bumping. NYE probably wasn't the best time to ask.

31 Dec
4 months ago

devk started a new conversation Polymorphic Relationship With 2 Different ID Columns

Hi,

I needed a polymorphic table for storing metadata, but my project has both UUIDs (binary) and IDs (uint). So I added both an uint and a binary id column and added a very hacky check for (which works for my needs so far) which one the relation should use .

Can this bite me in the ass in some way I didn't foresee and, if so, would you recommend another way:

<?php

namespace App\Traits\Model;

use App\Models\Metadata;

trait Metadatable
{
    public function metadata()
    {
        return $this->morphMany(
            'App\Models\Metadata',
            'metadatable',
            'metadatable_type',
            app(self::class)->getKeyName() === 'uuid'
                ? 'metadatable_uuid'
                : 'metadatable_id'
        );
    }
}

Thanks and happy new year!

10 Dec
5 months ago

devk left a reply on Disable DB Unique Checks For Tests

@TYKUS - @tykus Nice, thanks for the suggestion! Will look into it

Just the addition of ->afterCreatingState(..) saved me a ton of headaches, but there are still some problems that faker/factories don't help me solve (such as checking for complicated uniqueness across multiple columns or when creating multiple models)

devk left a reply on Disable DB Unique Checks For Tests

@REALRANDYALLEN - Hmm interesting, but this does indeed seem to work (unless I got lucky 10 times in a row).

Thanks!

devk left a reply on Disable DB Unique Checks For Tests

It's pretty complicated as there's a chain of factories being called and faker's ->unique() has no way of checking for uniqueness when creating multiple models at once.

Properly fixing the factories could easily take days and I'll do it when I have some spare time, which is not now.

devk started a new conversation Disable DB Unique Checks For Tests

Hi,

I want to disable unique checks when running tests. I have some poorly set up factories that I don't have time to fix and they sometimes generate records that don't agree with the unique checks.

I tried this:

public function setUp()
{
    parent::setUp();
    \DB::statement('SET UNIQUE_CHECKS=0;');
}

with no luck.

Any help greatly appreciated, thanks!

07 Nov
6 months ago

devk left a reply on [BUG] Going Back Returns JSON

Can confirm it doesn't happen on Firefox either.

From my testing it only happens on Chrome. It's updated to the latest version (it's not in my screenshot, but I've updated since) and it consistently gives me same bug.

Let me know if I can assist debugging this in any way.

devk left a reply on [BUG] Going Back Returns JSON

Tested in Safari. Cannot reproduce.

But in Chrome I consistently get the same problem on my threads. Other threads do not produce the same bug.

devk left a reply on [BUG] Going Back Returns JSON

See my edit. I narrowed it down more

devk started a new conversation [BUG] Going Back Returns JSON

How to reproduce:

  1. go here https://laracasts.com/discuss/channels/laravel/additional-data-on-default-laravel-auth-events
  2. click on any link (can also be an external link)
  3. click back in your browser (tested with latest Chrome release)
  4. get JSON for with the thread data
06 Nov
6 months ago

devk left a reply on Additional Data On Default Laravel Auth Events

Yeah the listeners might (will probably) be async, so I can't use request().

So currently I see 2 other, not too terrible, options:

  1. My original idea of listening to Illuminate\Auth\Events\Login with a sync listener and just triggering a custom event with the cookie data from the listener
  • Pro: the even would be explicit, easy to read
  • Con: seems super stupid to add an extra chain of event-listener in this cycle
  1. Your suggestion of handling this with cache
  • Pro: straightforward implementation
  • Con: seeing just the listener and the event, reader of the code would have a problem understanding what the Cache calls are doing, what is getting returned and especially where it's getting set

I'll sleep on it, see if someone has a better idea

devk left a reply on Additional Data On Default Laravel Auth Events

That would work. But it doesn't seem as verbose as having an event with the required properties set to public. Or implementing an interface with getters for the cookie data.

devk started a new conversation Additional Data On Default Laravel Auth Events

Hi, I'm trying to make use of specifically the Illuminate\Auth\Events\Login event. It works great out of the box, but I need access to some additional data on my listeners, specifically from some cookies at the time of login.

What would be a good way of saving data from a cookie and have it available in listeners attached to Illuminate\Auth\Events\Login event? Even to queued listeners that do not have access to the request.

I was thinking, if there was a way to override this specific method: fireLoginEvent() that would work. But I don't think there is. The class implements Macroable so I tried creating a macro named fireLoginEvent, but it doesn't override the implemented method.

Any other ideas? I would like to avoid creating a listener on the native event that would just trigger a new custom event for my case.

Thanks in advance

05 Nov
6 months ago

devk left a reply on When Does The `report()` Method Of An Exception Get Called?

It gets reported upon throwing the exception.

Here's how I tested it (Tinker seems to catch all exceptions I guess):

Route::get('/', function () {
    $a = new \App\Exceptions\TestException('test');
    info('here we are');
    throw $a;
});

and the exception:

<?php

namespace App\Exceptions;

use Exception;

class TestException extends Exception
{
    public function report()
    {
        info('reported!!');
    }
}

And the laravel.log after visiting /:

[2018-11-05 17:22:04] local.INFO: here we are [2018-11-05 17:22:05] local.INFO: reported!!

devk started a new conversation When Does The `report()` Method Of An Exception Get Called?

Hi,

I'm wondering when does the report() method on an exception get called?

Say that we have this code:

$a = new SomeCustomException(..);
dump('we\'re here');
throw $a;

Will the report() get called upon instantiating the exception or when the exception gets thrown?

Also I tried putting simple info('test'); into report() method of a custom exception and a) instantiate it in tinker b) throw it in tinker and it didn't log my 'test'. I'm thinking it only works on requests probably.

01 Nov
6 months ago
31 Oct
6 months ago

devk left a reply on Eloquent Resource `whenLoaded` Does Not Work As Expected Within `with` Method

This is my temporary solution:



    /**
     * Get additional data that should be returned with the resource array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function with($request)
    {
        if (! Auth::check() || ! $this->relationLoaded('user_picks')) {
            return [];
        }

        return [
            'meta' => [
                'user_picks' => OutcomeResource::collection(
                    $this->user_picks
                ),
            ],
        ];
    }

devk started a new conversation Eloquent Resource `whenLoaded` Does Not Work As Expected Within `with` Method

Hi,

here's the code I'm trying to make work:

<?php

namespace App\Http\Resources;

class ModelResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'user_picks' => AnotherModelResource::collection(
                $this->whenLoaded('user_picks')
            ),
        ];
    }

    /**
     * Get additional data that should be returned with the resource array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function with($request)
    {
        if (! auth()->check()) {
            return [];
        }

        return [
            'meta' => [
                'user_picks' => AnotherModelResource::collection(
                    $this->whenLoaded('user_picks')
                ),
            ],
        ];
    }
}

I'm trying to make the logic in with(..) method work (I want to load user_picks under meta and only when a user is logged in + the relation has been eagerly loaded). It's only replicated in the toArray() part because I wanted to double check if the same functionality works there. It does.

So - the toArray() part works perfectly, but the with() part dies when the relationship was not eagerly loaded with the next error:

testing.ERROR: Trying to get property 'map' of non-object {"exception":"[object] (ErrorException(code: 0): Trying to get property 'map' of non-object at ./vendor/laravel/framework/src/Illuminate/Http/Resources/Json/ResourceCollection.php:48) [stacktrace]

Any help appreciated, thanks!

26 Oct
7 months ago

devk left a reply on How To Tell If A Request Is Made To The API Routes

Yeah that seems good. For my use case, I think I'll actually settle for ! $request->hasSession() + (||) your suggestion.

Thanks!

devk started a new conversation How To Tell If A Request Is Made To The API Routes

Hi, so I'm trying to implement the render method of an Exception, but since I use the exception in both api routes and stateful routes, I need to be able to tell if it's api or not.

I could just check the first segment of the URL, but seems hacky. Maybe there's a way to check if the request went through api middleware? Or anything even more straightforward?

Thanks

25 Oct
7 months ago

devk started a new conversation Model Update Method That Would Return Updated Model

Hey

simple, code style question.

How would I make this a 1 liner:

public function update(Request $request, int $id)
{
       return new ModelResource(
            Model::findOrFail($id)->update($request->input())
        );
}

This doesn't work as ->update(..) returns a boolean. I also tried ->fill(..)->save(), but ->save() also returns a boolean.

Any suggestions, ideas? Is it possible?

Thanks!

21 Sep
8 months ago

devk left a reply on Storing Additional Data With A Request

@D9705996 Yeah that's pretty much perfect! Also, I used 3 other Spatie (Fractal, UUIDs, QueryBuilder) packages in the same project - have a lot of trust in their packages. The annoying part is generally just updating lots of packages and going through all the changelogs and making sure nothing breaks.

@Cronix Yeah that also seems like a great solution. In fact, seems like the Spatie package pretty much does this anyway

devk left a reply on Storing Additional Data With A Request

@D9705996 Interesting, will look into it. Though, I would prefer not to add another dependency for such a small thing.

@Cronix I'm using this on stateless api routes.

devk started a new conversation Storing Additional Data With A Request

So, I have a middleware that queries for a model with passed in api key. Similar to auth middleware.

Now, I don't want to query for that model again in my controller methods.

So currently I do this: $request['model'] = $model; and retrieve it with $request->model.

My question is if there's a better way of achieving this. I'm not a fan of that attribute being treated as input (it can also be retrieved with ->input('model'), which it clearly isn't.

Thanks in advance!

03 May
1 year ago

devk started a new conversation Model Factory That Would Create Related HasMany Models As Well

I'm looking for a way to create related hasMany models on the parent factory. Is that possible?

An example: a user can have many mails and possibly some other ->hasMany relations.

For my tests it would be extremely useful if I could define a factory for a user with a) with multiple mails b) a mail that is confirmed (column on mail model) c) ...

I'm looking for something along these lines:

$factory->defineAs(User::class, 'with_mail', function (Faker $faker) {
    $user = factory(User::class)->create();
    $mail = factory(UserMail::class)->create([
        'user_id' => $user->id,
    ]);
    return $user;
});

This doesn't work as the defineAs method expects to have raw attributes returned, but obviously, if I don't ->create() a user (but ->make() it instead), I can't assign them an email.

Is there a way to accomplish this with Eloquent factories?

26 Apr
1 year ago

devk left a reply on Retrieving Multiple Table Rows With Common Column

Are you sure you want a join here? Seems like you might want union instead.

This happens because container_id (and probably some other fields as well) is ambiguous.

Is the desired result to get data from all 3 tables in separate rows, or do you expect every row to have data from all 3 tables?

devk left a reply on Creating Non Reactive Copies Of Vue Data

Or just Object.assign(this.oldForm, this.form). Or this.oldForm = {...this.form}.

25 Apr
1 year ago

devk left a reply on Trying To Get Property Of Non-object - Default Fallback

Probably not the best idea and if you're not desperate. But you could override the getRelationValue($key) method with something like this:

public function getRelationValue($key)
{
    return parent::getRelationValue($key) ?? optional();
}

optional() will return null when you call some property on it. Of course, you could return some custom object that returns 'non-object data' on all properties instead, but you get the idea.

devk left a reply on Trying To Get Property Of Non-object - Default Fallback

That's beautiful. I had no idea that doesn't throw an error.

devk left a reply on Query To Eloquent Model

Well, my method is using the Eloquent relationship. Bobby's method is reproducing your query.

Can't have it both ways

devk left a reply on Query To Eloquent Model

I think what you want is something like:

$author = Author::withCount('books')->get();`

The query won't be the same, but it'll get you what you want using Eloquent. This assumes you have the relationship books() defined on the Author model.

devk left a reply on Trying To Get Property Of Non-object - Default Fallback

You could create a function on the model. Something like this:

class User extends Model
{
    public function extendedTitle()
    {
        return optional($user->extended->title) ?: 'non-object data';
    }
}

And call it like this: $user->extendedTitle().

Or you could create an accessor if you prefer.

devk left a reply on Refactor Store() Method When Handling More Than One Entities While Saving Data

A bit unclear which part of that can be reused and where. So hard to say for sure.

But let me give you an example of how I usually deal with reusable images.

  1. I make the images table have the polymorphic columns (see morphs), so that an image can belong to multiple models

  2. I, indeed, create a trait for that relationship. Something like this:

    trait Imagable { public function images() { return $this->morphMany(Image::class); }

     public function saveImage()
     {
          // save image logic
     }
     // Additional methods I might use
    

    }

  3. Add the trait to the models that can have images

    class SomeModel { use Imagable; }

  4. Now you have reusable image logic and can do something like this in your controllers:

    $someModel->saveImage(...);

I think that's a pretty good way of reusing the code.

devk left a reply on Detect When A User Leaves A Specific URL

Just wanted to say that I've had nothing but problems with onbeforeunload. Some browsers are more permissive than others with what you can and can't do with it and it's a pain to make it consistent and test for multiple browsers. It might work in 99+% of cases, but you might get some forever-restricted posts every now and then if it's your only method of closing the flag.

I truly believe the pinging method is your best choice here. You can, however, implement onbeforeunload method on top of it, to make the timing more accurate.

devk left a reply on Detect When A User Leaves A Specific URL

I think your safest bet will probably be to send ajax requests from client side every, say 30 seconds. And automatically remove the flag if no ajax requests were received for, say 2 minutes. Obviously, you can change the timeout to your liking.

devk left a reply on Load Model Maps On Demand

Can you give an example of what these maps do? Also, how are they called 100% of the time at the moment?

24 Apr
1 year ago

devk left a reply on Filter Many To Many Relation Result By Column In Pivot Table

Everything is correct except you need to use whereHas instead of with:

$normalEmployees = Employee::whereHas('workingCompanies', function ($query) use ($role) {
    $query->withPivot('employee_role')->wherePivot('employee_role',$role);
})->get();

devk left a reply on CORS Preflight Channel Did Not Succeed

You need to set header Access-Control-Allow-Origin

'Access-Control-Allow-Origin': 'http://yourAngularApp.com'