vkronlein

vkronlein

Member Since 3 Years Ago

Phoenix, AZ

Owner / Lead Developer at Periapt, LLC.

Experience Points 41,540
Experience Level 9

3,460 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 452
Lessons
Completed
Best Reply Awards 1
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.

30 Jan
2 weeks ago

vkronlein left a reply on Broadcasting Events Not Changing

Just for anyone else that comes across this ...

queue:restart

solves it.

vkronlein started a new conversation Broadcasting Events Not Changing

I'm writing some broadcast events and when I change the code in the event and then fire it again, it still broadcasts the old event data.

Is there some trick to ensure the new code is picked up?

So far the only way I've been able to reset this is to completely halt homestead and restart it.

Thanks.

24 Jan
3 weeks ago

vkronlein left a reply on Laravel-Echo-Server Installation On Forge With SSL Enabled With The Redis Broadcast Driver And Socket.io

@ashwinmram

I wasn't able to get the daemon to work. I have laravel-echo-server installed globally via nvm.

I used the command:

/home/forge/.nvm/versions/node/v8.15.0/bin/laravel-echo-server start

but I'm getting an error exited too quickly.

Any ideas on how to get this rolling?

07 Jan
1 month ago

vkronlein left a reply on Component Not Accessing Vuex State

@REALRANDYALLEN - Since my fetch method returns a promise I just swapped out some variable names and added a method to set a data property like so:

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
    created() {
        this.fetch().then((response) => {
            this.setCurrent()
        })
    },
    data() {
        return {
            current: ''
        }
    },
    computed: {
        ...mapGetters({
            statuses: 'statuses',
            latest: 'getLatest',
        }),
    },
    methods: {
        ...mapActions({
            fetch: 'fetchBuilderStatuses',
        }),
        close() {
            $('#status-modal').modal('hide')
        },
        setCurrent() {
            this.current = this.latest.class
        }
    }
}
</script>

No more errors, it is laggy when you load the page though which kinda sucks, but it works for now. My production server is really fast so I think it'll be fine.

Thanks so much for your help Randy, I appreciate it.

V

vkronlein left a reply on Component Not Accessing Vuex State

@REALRANDYALLEN - No love. I still get the same error.

Here is all the JS from my component, it's pretty basic, and I've never run across this error before.

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
    created() {
        this.fetch()
    },
    mounted() {
        console.log(this.current)
    },
    computed: {
        ...mapGetters({
            statuses: 'statuses',
            current: 'getLatest',
        }),
    },
    methods: {
        ...mapActions({
            fetch: 'fetchBuilderStatuses',
        }),
        close() {
            $('#status-modal').modal('hide')
        }
    }
}
</script>

Let me know if you want to see all the vuex pieces as well.

Thanks for the help!

vkronlein left a reply on Component Not Accessing Vuex State

@REALRANDYALLEN - let me try that and report back the results.

vkronlein left a reply on Component Not Accessing Vuex State

@REALRANDYALLEN - Makes sense to consider, but even the below returns null.

mounted() {
    console.log(this.current)
}

Furthermore I'm using current as a model on a div:

<div class="status" :class="current.class"></div>

Which is what's producing the error in the initial post.

06 Jan
1 month ago

vkronlein started a new conversation Component Not Accessing Vuex State

I have a component that has 2 vuex getters: statuses and getLatest which return statuses and latest from state. statuses being an array and latest is a null object.

I have an action fetchBuilderStatuses that fetches status messages from a remote Lumen install as a json array which contains latest which is the first message, and statuses which is a collection of all the messages. All pretty basic, the Lumen install has CORS installed and does correctly return all the data.

I'm importing mapActions and mapGetters from vuex of course.

My computed object on the component looks like so:

computed: {
    ...mapGetters({
        statuses: 'statuses',
        current: 'getLatest',
    }),
},

When using the chrome vue dev tool I can see that latest is being set in state correctly, it is an object that contains all my data as expected, as well as statuses which is set properly as well.

But in my component I'm getting the following error:

[Vue warn]: Error in render: "TypeError: Cannot read property 'class' of null"

If I console log this.current it is null.

This makes absolutely no sense to me. I use this same exact technique all over my app and never does this happen, my vuex state is always pulled in exactly as it should be.

Any ideas on why this might be happening?

If any additional code is needed just let me know.

14 Nov
3 months ago

vkronlein started a new conversation Homestead Box Won't Update

When running homestead up I get the 6.4.0 available message, so then I run homestead box update which downloads the 6.4.0 box, but then it doesn't upgrade. I run halt then up again and get:

==> homestead-7: A newer version of the box 'laravel/homestead' for provider 'virtualbox' is
==> homestead-7: available! You currently have version '6.3.0'. The latest is version
==> homestead-7: '6.4.0'. Run `vagrant box update` to update.

Running homestead box list :

laravel/homestead (virtualbox, 6.3.0)
laravel/homestead (virtualbox, 6.4.0)

How can I get this to update to 6.4?

06 Nov
3 months ago

vkronlein started a new conversation Accessing The User Session In A Job

Hey All.

I have a system of external applications (API's) that my users can access through a token/authorization system I built into the app.

Now they need to go the actual list of apps and connect manually. I've set up a login column in my table so that they can choose to connect on login per application, for the ones they use the most.

Currently when they connect, there is a handshake process that eventually returns a token from the external service that gets stored in their session.

When building the autoconnect on login Job, I've discovered that the session isn't able to be accessed as you normally would since the job runs independently.

I do have my user stored on the job class, how can I access that user's session from within a job.

I can add code if needed, but I think this is a pretty straight forward question.

30 Oct
3 months ago

vkronlein left a reply on Return Response For ManytoMany Attach

@staudenmeir

Yes that's the one I found when testing.

I decided to do a negative check since it's void if successful, this seems to work fine.

$insert = $user->applications()->attach($model, $pivotData);

if (! $insert) {
    // do stuff
}

Thanks for the help.

vkronlein left a reply on Return Response For ManytoMany Attach

@staudenmeir

Some sort of Builder query exception I assume, since there's no specific exception listed in the method?

vkronlein started a new conversation Return Response For ManytoMany Attach

Digging into the InteractsWithPivotTable trait I can see that attach returns void, but I need to figure out a way to determine if my attach call was successful so that I can return a response message to Vue.

Anyone have a solution or any ideas for this?

26 Oct
3 months ago

vkronlein left a reply on API Calls From Datatables Not Authorized

@Snapey

Yeah I'm at that point, I guess I'll just move them into the web routes, but I'd still like to know why this doesn't work as expected.

@cmdobueno

Using Laravel 5.5.44 and Passport 4.0.3

vkronlein left a reply on API Calls From Datatables Not Authorized

No this app isn't in a place yet to be able to be upgraded to 5.7. I took it over about a year ago and have been trying to slowly replace all the terrible spaghetti left by the previous dev.

It's in production, making that much more difficult as the owner is constantly adding new features so as to make getting it cleaned up and refactored that much more time consuming.

And no, I'm not modifying the request anywhere.

vkronlein left a reply on API Calls From Datatables Not Authorized

@cmdobueno

This doesn't make sense. By definition, the CreateFreshApiToken middleware adds a laravel_token cookie to each response that contains the authenticated user's information.

When I look at the my list of cookies in Chrome I can see that the cookie exists, with my api guard set to passport, Passport should resolve this cookie to push the user model on to the request object.

Clearly this isn't happening as my request object is completely empty.

vkronlein left a reply on API Calls From Datatables Not Authorized

@cmdobueno

I need to re-answer part of your initial question.

Other api calls do work when outside the auth:api middleware, but the call to user returns an empty response.

Route::get('/user', function (Request $request) {
    return $request->user();
});

returns nothing.

Event if I just return the $request I get nothing but an empty array.

Route::get('/user', function (Request $request) {
    return $request;
});

Response = []

Something is amiss here.

vkronlein left a reply on API Calls From Datatables Not Authorized

@D9705996

Yes CreateFreshApiToken is listed last in the stack.

protected $middlewareGroups = [
    'web' => [
        \App\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

vkronlein left a reply on API Calls From Datatables Not Authorized

@cmdobueno

Thanks anyway, hopefully Bobby will chime in here, he usually finds these things straight away.

I was trying to figure out how I can intercept this before it throws the 401 to see what's happening in Passport or wherever it's failing ... but I haven't had any luck doing that yet either.

vkronlein left a reply on API Calls From Datatables Not Authorized

@cmdobueno

Config uses Passport.

Bearer token shouldn't be needed, I'm consuming my own API as per the documentation: https://laravel.com/docs/5.5/passport#consuming-your-api-with-javascript

Yes everything works fine outside of the call to auth:api

First time I've tried to use the middleware.

Thanks for your help.

vkronlein left a reply on API Calls From Datatables Not Authorized

@bobbybouwmann

Any chance I can get you to weigh in on this?

Why can't I access my own API when it's behind the auth:api middleware? What do I need to do to fix this?

Thanks.

17 Oct
3 months ago

vkronlein left a reply on Events/Jobs Inside Event Listener Never Fire

That defeats the whole purpose of queueing the job.

16 Oct
3 months ago

vkronlein left a reply on Events/Jobs Inside Event Listener Never Fire

It seems that queue:work doesn't listen for events, only for jobs. A listener is basically just a job, so when the initial event fires, it creates a listener job which gets picked up by the work command.

But if you fire a new event during the handle process, this event is not being listened for.

But, once I switched both to jobs, they both fire as expected.

If however you run queue:listen this process does find new events within event handlers. Weird, but I need a queued job so skipping the events is fine.

vkronlein started a new conversation Events/Jobs Inside Event Listener Never Fire

Is there some reason why an event or job would not fire from inside the handle method of an event listener?

public function handle(SaveRecordPdf $event)
{
    $record = $event->record;

    if ($this->service->publish($record)) {
        Log::info($record->published_filename . ' was stored successfully.');

        // fire publish job
        PublishFile::dispatch($record); // never fires

        event(new SomeEvent($record)); // also never fires

    }
}

I know I've done this in earlier versions, this app is v5.5.44

Thanks.

15 Oct
4 months ago

vkronlein left a reply on API Calls From Datatables Not Authorized

@jlrdw @Cronix

It's not a datatables issue, I can't hit anything inside the auth:api middleware, even the default

axios.get('/api/user')
    .then(response => {
        console.log(response.data);
    });

fails using both axios and jquery. Always returns 401 Unathorized with the Unauthenticated message.

And before you ask, I do have passport set as my auth driver for the api routes.

@D9705996

Yes, when I remove the routes from behind the middleware it works perfectly.

Here's the code that's inside the view, not sure how this would help but as requested:

@push('scripts')
    <script>
        $(document).ready(function() {
            $('#datatable-users').DataTable({
                'processing': true,
                'serverSide': true,
                'ajax': '/api/datatables/users',
                'pageLength': 25
            });
        });
    </script>
@endpush

vkronlein started a new conversation API Calls From Datatables Not Authorized

Hello all.

I have some datatables being called via api in some views. There exist from the previous developer.

I just realized that they were outside of any authentication and available to the public, so I moved it inside of the auth:api middleware and not I get a 401.

Route::group(['middleware' => 'auth:api'], function() {
    //dd(request()->cookie('laravel_token')); // always produces a valid token
    Route::get(
        '/datatables/users', 
        'Builder\[email protected]'
    );
});

I included the CreateFreshApiToken middleware from Passport and with the commented out dd call I can see that a valid token is being sent on each request.

Why would I be getting a 401?

12 Oct
4 months ago

vkronlein left a reply on Relationships Always Null

@Cronix

I figured, but those aren't the id's from the table.

@staudenmeir

Changed the incrementing but no love, also needed to add keyType = 'string' and then this did the trick.

Thanks everyone for all your help, much appreciated.

vkronlein left a reply on Relationships Always Null

@staudenmeir

They are the standard Passport migrations, let me grab them from github.

public function up()
{
    Schema::create('oauth_access_tokens', function (Blueprint $table) {
        $table->string('id', 100)->primary();
        $table->integer('user_id')->index()->nullable();
        $table->integer('client_id');
        $table->string('name')->nullable();
        $table->text('scopes')->nullable();
        $table->boolean('revoked');
        $table->timestamps();
        $table->dateTime('expires_at')->nullable();
    });
}

public function up()
{
    Schema::create('oauth_refresh_tokens', function (Blueprint $table) {
        $table->string('id', 100)->primary();
        $table->string('access_token_id', 100)->index();
        $table->boolean('revoked');
        $table->dateTime('expires_at')->nullable();
    });
}

vkronlein left a reply on Relationships Always Null

@staudenmeir

array:2 [▼
  0 => array:3 [▼
    "query" => "select * from `oauth_access_tokens`"
    "bindings" => []
    "time" => 0.38
  ]
  1 => array:3 [▼
    "query" => "select * from `oauth_refresh_tokens` where `oauth_refresh_tokens`.`access_token_id` in (?, ?, ?, ?, ?, ?, ?, ?)"
    "bindings" => array:8 [▼
      0 => 0
      1 => 3
      2 => 13
      3 => 44
      4 => 85
      5 => 2855414
      6 => 5850233
      7 => 8646257075
    ]
    "time" => 0.63
  ]
]

Can you explain what the bindings are here?

vkronlein started a new conversation Relationships Always Null

I'm sure I must be missing something simple.

I've created local models for the OAuth tables created by Passport.

I'm trying to create a one to one relationship between oauth_access_tokens and oauth_refresh_tokens

As per the docs:

Eloquent determines the foreign key of the relationship based on the model name.

The refresh table column is access_token_id to reference the parent table id.

namespace App;

use Illuminate\Database\Eloquent\Model;

class AccessToken extends Model
{
    protected $table = 'oauth_access_tokens';

    public function refresh()
    {
        return $this->hasOne(RefreshToken::class);
    }
}

As per the docs:

Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method.

Thusly if my column name is access_token_id and my method name is access_token My belongs to model should like like so:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class RefreshToken extends Model
{
    protected $table = 'oauth_refresh_tokens';

    public function access_token()
    {
        return $this->belongsTo(AccessToken::class);
    }
}

It seems that the relationships are created because I can eager load them without any errors, but they are consistently null. For both relationships.

If I call either of these:

$tokens = AccessToken::with('refresh')->get();

foreach ($tokens as $token) {
    $token->refresh // always has a value of null
}

$tokens = RefreshToken::with('access_token')->get();

foreach ($tokens as $token) {
    $token->access_token // always has a value of null
}

What am I missing, this usually just works without a problem.

Thanks

01 Sep
5 months ago

vkronlein left a reply on File Not Found For Download

@Dry7

Uh ... no. These downloads aren't public, aside from which, I already have the storage link set up.

31 Aug
5 months ago

vkronlein started a new conversation File Not Found For Download

I'm getting a FileNotFoundException using the Storage Facade when the file is indeed there. I'm looking at it in the damn folder. The path and filename are correct, I've triple checked everything ...

The weird part is I'm downloading it from another section via controller using response()->download($same->path) and it works perfectly.

If I use Storage::get($same->path) it returns the file as a string ... but the download method can't seem to find it.

I've read the docs ... and I missing something obvious?

Thanks.

14 Jul
7 months ago

vkronlein started a new conversation Single Form For New And Editing Data

Can anyone tell me what's the best way for handling data for a form so that I can use my form for both editing an existing data object, or creating a new one?

If an item is being editing it's being pulled in via mapGetters from Vuex, but it seems like if I'm doing it this way the new item form doesn't work correctly.

Should I create individual props for each form field and set them to null or data based on my pulled in Vuex computed props or is there an easier way to format this so it works consistently?

Any help would be greatly appreciated.

If you need any code please let me know what you want to see and I'll happily post it up.

29 Jun
7 months ago

vkronlein started a new conversation Computed Property Won't Render

I can't figure this one out.

I have a vuex-binding in my component that shows in the vue dev tools as correctly populated, then an additional computed property to select a given key from the object.

but when I try and render that property as v-html or v-model it throws an error "TypeError: Cannot read property '1' of null"

computed: {
    ...mapGetters({
        instructions: 'wizard/instructions'
    }),
    standard() {
        return this.instructions[this.isActive]
    }
},

In the above,

isActive is numerical and represents a given key of the property to load

In my vuex dev tool I have

data
    isActive: 1
    isOpen: false

computed
    standard: "the html of the correct instruction"

vuex bindings
    instructions: Object

In my template I have a simple bootstrap panel body div

<div class="panel-body" v-html="standard"></div>

If I remove the binding to standard in the div the error stops, but with it in I get the error.

Any ideas would be helpful.

Thanks.

18 Jun
7 months ago

vkronlein left a reply on Extending ConsoleMakeCommand

@bobbybouwmann

Yeah honestly I think that should be changed for abstract methods. The purpose of declaring something abstract is so that it has no set up, which I think should include the signature.

We already have strict signature enforcement on Interfaces ...

Anyway, I was able to resolve it using reflection and middleware, but it should be easier to resolve this type of problem.

Thanks.

16 Jun
7 months ago

vkronlein left a reply on Extending ConsoleMakeCommand

@bobbybouwmann

How would I go about enforcing that a class has a given method, but making the signature flexible?

For instance I want to make my action classes all adhere to an interface that includes the __invoke() method but can also have variables passed in, or be able to type hint classes in the signature.

I tried this:

namespace App\Domain\Contracts;

interface ActionContract
{
    public function __invoke($class = null);
}

Then in my action :

public function __invoke(UserRepository $users)
{
    return $this->responder->send();
}

But I'm getting the dreaded must be compatible with error.

I want to ensure that the actions aren't creating traditional crud methods in order to keep the SOC principle intact by default.

I'll also need this type of functionality for my Service classes as I want to force the handle method to receive some optional params while enforcing others.

Thanks.

15 Jun
8 months ago

vkronlein left a reply on Extending ConsoleMakeCommand

@bobbybouwmann

Yeah normally I would agree with you, but I really like the idea of ADR a lot. And I think the pattern in general is better for modern web apps. I'm constantly trying to clean up controllers and keep SOC and DRY principles.

@JeffreyWay has really helped me clean up my coding and reusability principles, and at least for me, ADR is the next step in this journey.

Thanks again for the assist.

vkronlein left a reply on Using Different Namespace For Controllers And How App\Http\Controllers Works.

Yeah I would recommend reading up on autoloading in PHP so you'll better understand how classes and files are loaded.

(PSR)[https://www.php-fig.org/psr]

vkronlein left a reply on Trying To Get Property Of Non Object

Wow ... this is like a skit on SNL.

vkronlein left a reply on Extending ConsoleMakeCommand

@bobbybouwmann

I'm such and idiot ....

Look at the namespace .... should be Commands not Command

Thanks for your help man.

I'd love to get your opinion on how I've structured everything if you're interested.

https://source.codemafia.io/codemafia/laravail

14 Jun
8 months ago

vkronlein left a reply on Extending ConsoleMakeCommand

@bobbybouwmann

Any ideas?

All my other commands are working great.

vkronlein left a reply on Extending ConsoleMakeCommand

<?php

namespace App\Domain\Console\Command;

use Illuminate\Foundation\Console\ConsoleMakeCommand as BaseConsoleMakeCommand;

class ConsoleMakeCommand extends BaseConsoleMakeCommand
{
    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__.'/stubs/console.stub';
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Domain\Console\Commands';
    }
}

vkronlein started a new conversation Extending ConsoleMakeCommand

I'm creating an ADR version of the latest version of Laravel, mostly for my own use, but I will make it public for anyone who wants it.

As part of this I've moved all domain related stuff inside the domain directory, so this requires creating new make commands for generating classes to the correct location.

For all of these it's been very straightforward, create a new MakeCommand which extends the original one, change the namespace section, copy over the stub and make whatever changes are needed and register it in the Kernel.

Until ... the ConsoleMakeCommand.

 Whoops\Exception\ErrorException  : Cannot declare class App\Domain\Console\Command\ConsoleMakeCommand, because the name is already in use

  at /Users/vincek/Code/adr/web/app/Domain/Console/Commands/ConsoleMakeCommand.php:29
    25|     protected function getDefaultNamespace($rootNamespace)
    26|     {
    27|         return $rootNamespace.'\Domain\Console\Commands';
    28|     }
  > 29| }
    30| 

This error doesn't make sense to me, I can't declare it in the file it's in, because it's already declared in the file it's in .... what the heck?

Can anyone explain to me how I can get this done?

Thanks.

06 Jun
8 months ago
22 Apr
9 months ago

vkronlein left a reply on Service Provider Not Publishing Config File

@Cinek

All the paths are good, as I said, it will publish if I select it from the list with just

php artisan vendor:publish

Perhaps I need quotes around my class name?

vkronlein started a new conversation Service Provider Not Publishing Config File

In my package, I have a config file to publish but in 5.6 it won't publish the file:

public function boot()
{
    $this->publishes([
        __DIR__ . '/../config/generator.php' => config_path('generator.php'),
    ]);
}

When I run:

php artisan vendor:publish --provider=Empress\Generator\GeneratorServiceProvider

All I get is Publishing complete. but nothing is published.

It will however publish if I use just

php artisan vendor:publish

I can then select the provider from the list and it does publish.

Is there something I'm missing here or something that's changed?

Thanks.

29 Mar
10 months ago

vkronlein left a reply on Laravel Is A Giant Waste Of Time

HAHAHAHAHAHA This was the best thing I've seen all month!

And to think it's been here for 2 years. Awesome.

Poor old @dazed067 is probably rocking a mullet and a Motorola flip phone, cause you know ... it takes a minute to set up that stupid iPhone ... I just wanna turn it on and start dialing.

Fabulous!

vkronlein started a new conversation API Resource Custom Conditional Pivot

The documentation stays to do a conditional pivot I have submit a closure like so:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'expires_at' => $this->whenPivotLoaded('role_users', function () {
            return $this->pivot->expires_at;
        }),
    ];
}

I have a resource that requires 10 different columns from the same pivot table, is there not a way to wrap these all within the same closure? Seems nuts to have to whenPivotLoaded 10 different times on the same pivot table.

Anyone?

27 Mar
10 months ago

vkronlein left a reply on Checking For Deep Nested Relations For APIResources

@ahmedmsvb

Thanks. I searched but didn't find that one. That might work.

vkronlein started a new conversation Checking For Deep Nested Relations For APIResources

Hey All.

I have a project I've taken over that's already in production, so no blame for the database design please =)

I've been tasked to build an API which is coming along nicely, but I've run into a snag that I'd like to resolve, it's not life ending, but if there's a way to accomplish this I'd like to.

I'd like to be able to omit certain columns from my resource depending on whether relations and nested relations are loaded.

Here's the case I'm working on.

  1. My record model has a product relationship
  2. My product model has a company relationship
  3. The records table has both a company_id and product_id

I'd like to show the model resource if the model has been loaded, or else the column value if not.

For direct relations this is a snap

In RecordResource:

$product = $this->relationLoaded('product') 
            ? new ProductResource($this->product) 
            : $this->product_id;

return [
    'id' => $this->id,
    'company_id' => $this->company_id,
    'format_id' => $this->format_id,
    'stage_id' => $this->stage_id,
    'archived' => $this->archived,
    'created' => $this->created_at->format('Y-m-d H:i:s'),
    'updated' => $this->updated_at->format('Y-m-d H:i:s'),
    'published_filename' => $this->published_filename,
    'published_at' => $this->published_at,
    'screened' => $this->screened->format('Y-m-d H:i:s'),
    'inventory_type' => $this->inventory_type,
    'leed_calc' => $this->leed_calc,
    'leed_display' => $this->leed_display,
    'no_accessory' => $this->no_accessory,
    'product'  => $product,
];

In ProductResource:

$company = $this->relationLoaded('company') 
            ? new CompanyResource($this->company) 
            : $this->company->name;

return [
    'id' => $this->id,
    'name' => $this->name,
    'archived' => $this->archived,
    'created' => $this->created_at->format('Y-m-d H:i:s'),
    'updated' => $this->updated_at->format('Y-m-d H:i:s'),
    'company' => $company,
];

These work perfectly since they are direct relations.

But if you look in the RecordResource array, I'd like to be able to remove the company_id key if company has been loaded in the ProductResource.

I know that having that company_id in the table is redundant, but once again I didn't design the database and there's no changing it now.

Is there a way to test whether the company has been loaded from within the RecordResource given that it's nested?

Thanks.