mikepmtl

Member Since 2 Years Ago

Palm Harbor, Florida

Senior Software Engineer at Honeyfund

Experience Points 14,120
Experience Level 3

880 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 130
Lessons
Completed
Best Reply Awards 0
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.

21 Apr
4 weeks ago

mikepmtl started a new conversation Auth::id Returns Null In ServiceProvider When Feature Testing

I have a package I wrote for User/Role/Group permissions that loads up through a ServiceProvider.

It works fine generally, but for some reason in Feature Tests Auth::id() returns null;

I am "actingAs()" in the test.

Any idea why this works just fine normally but fails to give me an id in feature tests?

My work around for now is I just re-boot the class at the start of the test, but it is annoying me and I would like to know why.

Thanks, Mike

    /**
     * @test
     */
    public function it_allows_an_admin_with_permission_to_view_their_payment_type(): void
    {
        $response = $this->actingAs($this->admin)->json('GET', '/users/resources/payment-types/' . $this->payment_type->id);
        $response->assertStatus(200);
        $response->assertJsonFragment(['userid' => $this->owner->id]);
        $response->assertHeader('content-type', 'application/json');
    }
<?php


namespace App\Providers;

use App\Permissions\Acl;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;

/**
 * Provides Permissions for Users and Roles
 *
 * @package App\Providers
 */
class AclServiceProvider extends ServiceProvider implements DeferrableProvider
{
    /**
    * Indicates if loading of the provider is deferred.
    *
    * @var bool
    */

    /**
     * AclServiceProvider constructor.
     *
     * @param \Illuminate\Foundation\Application $app
     */
    public function __construct(Application $app)
    {
        parent::__construct($app);
    }

    /**
     * Bootstrap the application services.
     *
     * @param \App\Permissions\Acl $acl
     *
     * @return void
     */
    public function boot(Acl $acl): void
    {
        $acl->boot(Auth::id());
    }


    /**
     * Register the application services.
     *
     * @return void
     *
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */
    public function register(): void
    {
        $this->app->singleton(Acl::class, function ($app) {
            return new Acl();
        });
    }

    /**
     * What we are providing.
     *
     * @return array
     */
    public function provides(): array
    {
        return [Acl::class];
    }
}
14 Apr
1 month ago

mikepmtl left a reply on Questions For Horizon, Multiserver And Job Handling

So did you ever figure this out?

Are there any issues running horizon on multiple servers all using the same Redis server and database?

Thanks.

13 Feb
3 months ago

mikepmtl left a reply on Please Help Me Pick A Front End!

Thanks for the replies.

11 Feb
3 months ago

mikepmtl started a new conversation Please Help Me Pick A Front End!

If you were starting a medium size project today with a Laravel back end, which front end would you choose between VueJS and React? Why?

I am looking for as many replies as possible. Even it is just one word. :)

Thank you very much!

10 Feb
3 months ago

mikepmtl left a reply on Is It Necessary To Always Type "php Artisan"? Why Not Just "artisan"

What operating system are you using? Not only do I alias artisan, but 2 of my favorites are:

alias tinker='php artisan tinker'
alias tinkerd='php -dxdebug.remote_autostart artisan tinker'

The latter allows me to run code that my debugger will catch inside of tinker.

mikepmtl left a reply on How Do I Get Last Inserted Data Only

@mwspacellc answer is correct.

However you are not guaranteed on getting the last item YOU inserted, because of a possible race condition of course. You are simply getting the LAST inserted row (which could have been triggered by someone else). I'm not sure of your circumstance, but just wanted to point that out.

$user = DB::table('users')
            ->latest()
            ->first();

mikepmtl started a new conversation Using Echo In Nova Cards, Tools Etc.

I'm just trying to figure out the best way to use Echo inside of Nova.

What I would prefer would be available globally the way axios, moment and loadash are available.

What I am currently doing for a card is adding this to card.js.

import Echo from 'laravel-echo'

window.Pusher = require('pusher-js');
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'xxxxxxxxxxx'
});

I am just wondering if anyone else has used echo with Nova and what their approach has been.

09 Feb
3 months ago

mikepmtl left a reply on Predis Many Issues

Why not try using the Redis PHP extension instead?

Not sure what OS or PHP version you are running, but generally it's as easy as "apt install php-redis" and then in your cache config, set the redis driver from predis to redis.

'redis' => [
    'driver' => 'redis',
    'connection' => 'default',
],
22 Jan
3 months ago

mikepmtl left a reply on Using Vue2-filters In A Nova Tool

I finally got it to work...

Inside of the tool.js file I added:

    import Vue2Filters from 'vue2-filters';

    Nova.booting((Vue, router) => {

    Vue.use(Vue2Filters);

    router.addRoutes([
        {
            name: 'nova-user-report',
            path: '/nova-user-report',
            component: require('./components/Tool'),
        },
    ])
});

Inside of Tool.vue I have:

....
....
</template>

<script>

import Errors from 'laravel-nova';
import Vue2Filters from 'vue2-filters';
import moment from 'moment';

export default {

    mixins: [Vue2Filters.mixin],

....
....

mikepmtl started a new conversation Using Vue2-filters In A Nova Tool

I am trying to use vue2-filters (https://www.npmjs.com/package/) in a Nova Tool.

I installed vue2-filters via npm install.

Inside of Tool.vue I have added the import. I am not receiving any errors in the console, but the values are not being formatted.

<template>
        <div>
            {{ username | uppercase}}<br/>
            {{ amount | currency }}</br>
        </div>
    </template>

    <script>

        import Vue2Filters from 'vue2-filters';

        export default {

            mixins: [Vue2Filters.mixin],

            data: () => ({
            username: "[email protected]"
            amount: 103.95,
        });
    }
/* Scoped Styles */

What am I doing wrong?

16 Dec
5 months ago

mikepmtl left a reply on Dusk Click Element In Iframe

Does this still work for anyone using Dusk ^3.0 (Laravel 5.6).

It worked for me using Laravel 5.4. But since upgrading, it is no longer working for me?

The macro itself does not seem to have any errors, but Dusk is unable to find any selectors in the iframe.

08 Nov
6 months ago

mikepmtl started a new conversation Configs For Nova Custom Tools

I am wondering what would be the best practice to use config() data in a Nova Custom Tool.

I have not seen anyone publishing configs in Tools yet. No sure if it is even possible. I have seen some simply using env(), which I always thought was discouraged.

I have also seen people simply using existing configs, such as config/services.php.

I could not find anything about it in the Nova docs.

Does anyone have any recommendations?

mikepmtl started a new conversation Testing Nova Custom Tools

I've been looking through some other Nova custom tools on GitHub, and for the ones I've gone through, I've noticed none of them included any tests.

It seems odd to me, as I like developing using TDD.

I'm wondering if the best way to test would be to simply create a new abstract TestCase class that extends Illuminate\Foundation\Testing\TestCase inside of my components tests/ directory.

Is anyone writing tests for their Nova Custom Tools?

06 Oct
7 months ago

mikepmtl left a reply on Register Middleware Via Service Provider

In case anyone else is looking for an answer. In your Service Provider, you simply need to get the app['router'] and add your Middleware to it. You can add it to a group, or as an alias to be used in the routes file (web.php etc.).

/**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot(): void
    {

        /** @var Router $router */
         $router = $this->app['router'];
         
        $router->aliasMiddleware('mymid', MyMiddleware::class);
        // or
        $router->pushMiddlewareToGroup('web', MyMiddleware::class);

    }
03 Oct
7 months ago

mikepmtl started a new conversation Decrement With Multiple Relationships. About To Go DB::update()....

Having a difficult time getting this query ran using eloquent. I am simply trying to decrement the quantity in a users wishlist when an order is placed. I can easily get all the order items and loop through them to update the wishlist_items quantities. But I was hoping to get it all done in one query without looping.

Schema:

products:
    ‘id’
    ‘name’
    ‘use_quantity’

orders:
    ‘id’
    ‘customer_name’

order_items
    ‘id’
    ‘order_id’
    ‘product_id’
    ‘wishlist_item_id’
    ‘quantity’

wishlist_item:
    ‘id’
    ‘product_id’
    ‘quantity’

The SQL I am trying to achieve would be something like:

UPDATE wishlist_items w, order_items i, products p, orders o 
SET w.quantity = w.quantity - i.quantity
WHERE w.product_id = p.id
AND p.use_quantity = 1
AND i.product_id = p.id
AND i.order_id = $order_id;

After many different statements, this is where I am at, but it is not working...:

$result = $order->order_items()
    ->with(['product' => function($q){
        $q->where('use_quantity', true);
    }])->with(['wishlist_item'=>function($q){
        $q->increment('quantity');
    }])->get();

Can this be done? Or do I need to loop through the OrderItem's or go with raw SQL?

I am also thinking maybe I need to add a relationship for an Order to have many WishlistItem through OrderItem?

Thanks in advance for any suggestions.

24 Sep
7 months ago

mikepmtl left a reply on Dusk Click Element In Iframe

I take it you guys only register it in 'local' or 'testing' environments?

18 Sep
8 months ago

mikepmtl left a reply on How To Unit Test The Requeue/failure Of A Job?

assertPushed() and assertNotPushed() are not testing that a job failed. They only tests if a job was queued or not.

01 Feb
1 year ago

mikepmtl started a new conversation Is There No Built-in Query Caching In Laravel?

I saw in the docs in Laravel 4.x there was a remember() method to cache DB queries.

I don't seem to be able to find it in Laravel 5.x.

I have found an external packages like: https://github.com/dwightwatson/rememberable

It would also be easy enough to write in some query caching using Laravel's Cache class, but I just want to make sure I am not missing anything.

Is there no Core query caching in Laravel 5.x?

27 Jan
1 year ago

mikepmtl left a reply on How To Test A $model->create(); Failure.

Thanks @skliche.

I actually found the solution I was looking for after a lot of Googling. I will post it here in case anyone ever searches it.

I am actually using a repository patterns with my models and calling the repository class.

But I think the issue is that I am instantiating the repository class using app( ItemsRepository::class ); So the mock was never being called.

So the key to getting Mocking to work for me was adding this line:

$this->app->instance( ItemsRepository::class, $mock );

As in:

        $mock = \Mockery::mock( ItemsRepository::class );
        $mock->shouldReceive('create')->withAnyArgs()->andReturn( null )->once();
        $this->app->instance( ItemsRepository::class, $mock );

Once I registered the class with the mock, all worked as expected.

mikepmtl left a reply on How To Test A $model->create(); Failure.

I am pretty sure Mocking is the way to go here. But I am using Reflection to access the method. The mock object nevers seems to be called.

mikepmtl started a new conversation How To Test A $model->create(); Failure.

I am stumped on how to test a failure in a create() method. Given a function like:

/**
     * Add an item.
     *
     * @param string $name
     *
     * @return \App\Item|null
     */
    public function addItem( $name )
    {

        $item = $item->create([
            'name' => $name,
        ]);

        if ( ! $item ){
            return false;
        }

        return true;

    } 

How would I test for false? I need create to fail (simulating a DB error perhaps).

13 Dec
1 year ago

mikepmtl left a reply on Laravel And The EAV Model

@here For the next person, I found another more recently updated project which is originally based on @IsrealOrtuno's code.

https://github.com/rinvex/attributes

mikepmtl left a reply on Laravel And The EAV Model

@IsraelOrtuno I noticed it has a message saying being re-written. But no links. Has this been abandoned?

23 Nov
1 year ago

mikepmtl left a reply on Losing Middleware Request Variables When Using Illuminate\Foundation\Http\FormRequest

The other thing that works is to simply grab the Request object in the controller action using the request() helper.

(Adding this for anyone else searching for solutions)

mikepmtl left a reply on Losing Middleware Request Variables When Using Illuminate\Foundation\Http\FormRequest

I found a nice discussion about it here: https://github.com/laravel/framework/issues/10791#issuecomment-206198743

But this seems like a bug to me. The objects should be the same or merged IMHO.

The solution I found for now is to inject both into the controller action.

The form request must be first or it is ignored.

    /**
     * @param \Illuminate\Http\Request              $request
     * @param \App\Http\Requests\CartAddItemRequest $form_request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function addItem( Request $request, CartAddItemRequest $form_request )
    {

mikepmtl started a new conversation Losing Middleware Request Variables When Using Illuminate\Foundation\Http\FormRequest

I have middleware that adds information to requests such as geoip info etc.

It simply uses the request injected into handle() and creates a variables with the data.

$request->location = [ LOCATION_DATA ];

This is easily accessible in controller actions by injecting the request and accessing the variable.

However when using a Illuminate\Foundation\Http\FormRequest those variable are no longer there in the request.

I would think that A Illuminate\Foundation\Http\FormRequest or a Illuminate\Http\Request would be the same object, but it does not seem to be.

<?php


namespace App\Http\Middleware;

use Closure;
use \Illuminate\Http\Request;


/**
 * Class RequestVars
 *
 * @package App\Http\Middleware
 */
class RequestVars
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle( Request $request, Closure $next)
    {

        // Add in Geo location Data
        $ip = geoip()->getClientIP();
    $location = geoip()->getLocation( $ip );
    $request->location = $location['attributes'];

        return $next($request);

    }
}

In the controller.

    /**
     * @param \App\Http\Requests\CartAddItemRequest $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function addItem( CartAddItemRequest $request )
    {


        $item_id  = $request->input('item_id');
        $quantity = $request->input('quantity', 1);

        ...

        return redirect( $url );

    }
19 Oct
1 year ago

mikepmtl started a new conversation Elegant Way To Only Have Certain Scheduled Jobs Run On ALL Webservers

I am trying to think of an elegant way to have 1-2 scheduled jobs run on all web servers, and all the other scheduled jobs only run on a dedicated jobs servers.

I was thinking perhaps setting a value in .env and I can check for that value in Kernel.php schedule() method to limit what it will see. But I was wondering if other people had better ideas.

02 Jul
1 year ago

mikepmtl left a reply on Laravel And Vue.js Instances On Different Page

@ElpsySec

I think a lot of people would like to use Vue in this manner.

I understand it would be a lot of work, and it is a big ask, but you know what would be amazing, some simple example of this on GitHub.

A laravel project, with 2 different controllers (pages).

Each one loading a specific "page component" with the parent component for shared data.

I've been exploring this for the past couple of days now. I was about to create one "app.js" per page, but that doesn't seem right.

I am use to name spacing all my JS and then simply calling an init method on page loaded for the namespace that represents that page.

Your method seems similar to that.

21 Jun
1 year ago

mikepmtl left a reply on DB::beginTransansaction Still Committing Immediately

So I figured out what is causing it not to work, but not why exactly. If I remove the "connection" transactions work as expected.

DB::beginTransaction();

    try {

        DB::table('users')->where('id', 1)->update(['user_group_id' => 100]);

        throw new \Exception('Some new exception');

        DB::commit();

    } catch ( Exception $ex ){

        DB::rollBack();
    }

I do not see any difference between the configs between the default connection and the "giftcard" connection. I am thinking this is a bug in Laravel 5.4?

mikepmtl started a new conversation DB::beginTransansaction Still Committing Immediately

I am trying to use DB::transactions but it does not seem to be working for me.

DB::beginTransaction();

    try {

        DB::connection('giftcard')->table('redemption')->where('id', 736)->update(['status' => 'CREATED']);

        throw new \Exception('Some new exception');

        DB::commit();

    } catch ( Exception $ex ){
        DB::rollBack();
    }

If I place a breakpoint before throwing the exception I can see the status being updated in the database (MySQL 5.5) immediately before even reaching the commit.

The Database config is defines as:

'giftcard' => [
            'driver' => 'mysql',
            'read' => [
                'host' => env('DB_GIFTCARD_READ_HOST', '127.0.0.1'),
            ],
            'write' => [
                'host' => env('DB_GIFTCARD_WRITE_HOST', '127.0.0.1'),
            ],
            'port' => env('DB_GIFTCARD_PORT', '3306'),
            'database' => env('DB_GIFTCARD_DATABASE', 'forge'),
            'username' => env('DB_GIFTCARD_USERNAME', 'forge'),
            'password' => env('DB_GIFTCARD_PASSWORD', ''),
            'unix_socket' => env('DB_GIFTCARD_SOCKET', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_general_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => 'InnoDB',
        ],

Transactions work fine when using query in a mysql client.

Are there any other settings I need to change in PHP or Laravel to enable DB Transactions?

Thanks, Mike

04 Jun
1 year ago

mikepmtl left a reply on Get Session By Session ID

Or of course no need to decrypt if you are not using cookie encryption as set in config/sessions[ 'encrypt' => false ]

What did take me a minute to figure out, was that at least for Redis as a store, the session data is double serialized.

Using a web route to test this, you can get to the data like:

Route::get('/session', function () {

    echo "<pre>";
    $cookie = Request::cookie( 'laravel_session' );
    $sess = Redis::get('laravel:' . $cookie);
    print_r($sess);

    echo "\n\n\n\n=======================\n\n\n\n";

    $sessdata = unserialize( unserialize( $sess ) );
    print_r( $sessdata );

});

Of course if you changed your prefix you will need to change the 'Redis::get' key.

29 May
1 year ago

mikepmtl started a new conversation Testing Laravel Slack Notifications Always Fail

Not sure what I am doing wrong here, but no matter what I try my test using the example in the Laravel docs never passes. Everything else works just fine. But the test will not pass.

I have Notifiable Model call SlackWebHook

class SlackWebhook extends Model
{

    use Notifiable;

    protected $table = 'slack_webhooks';


    /**
     *
     * The endpoint for Slack notifications
     *
     * @return mixed
     */
    public function routeNotificationForSlack(){

        return $this->url;

    }
}

My Notification looks like (I removed all the message content for clarity)

class DailySlackGiftCardReportNotification extends Notification
{

    use Queueable;

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $webhook
     * @return array
     */
    public function via( $webhook )
    {
        return ['slack'];
    }


    /**
     * Get the slack representation of the notification.
     *
     * @param  mixed  $webhook
     * @return SlackMessage
     */
    public function toSlack( $webhook )
    {

        $message = new SlackMessage();

        $message->success()
            ->content('Hello');

        return $message;

    }


}

And my test based on the Laravel Docs using assertSentTo()

 /**
     * Test Slack Notification.
     *
     * @test
     * @return void
     */
    public function daily_gift_card_slack_notification_sent()
    {

        Notification::fake();

        $webhook = SlackWebhook::where('channel', '@gcstats')->first();

        Notification::assertSentTo(
            $webhook, DailySlackGiftCardReportNotification::class
        );
    }

If I try an AssertNotSentTo it passes. :) Of course, I would like it to pass being sent.

Any ideas what might be going on?

Thanks, Mike

mikepmtl left a reply on Artisan Make:model Specify The Directory And Namespace?

It will create the model file, the problem however is you need to define the table if you do this.

For: php artisan make:model "BackOffice\User"

Eloquent will be looking for a table named "users".

What I would expect is for Eloquent to look for a table named "back_office_users".

24 May
1 year ago

mikepmtl left a reply on MIX: How Can I Run Only Running A Subset Of My Webpack.mix.js File

I think you misunderstood. Basically I am using grunt to run Mix.

That was I can still use grunt for other tasks as well.

mikepmtl left a reply on MIX: How Can I Run Only Running A Subset Of My Webpack.mix.js File

I think what I will do is still use grunt to run my other tasks but include a task to run "npm run dev" and so on.

Thanks

mikepmtl left a reply on MIX: How Can I Run Only Running A Subset Of My Webpack.mix.js File

I achieve some separation simply by defining several actions in webpack.mix.js as:

mix.combine([ 'resources/assets/js/public.js', 'resources/assets/js/Public/*/.js' ], 'public/assets/js/public.js').version();

mix.sass('resources/assets/sass/app.scss', 'public/assets/css').version();

mix.sass('node_modules/bootstrap/scss/bootstrap.scss', 'public/assets/css').version();

I guess what I am missing from gulp and grunt is the ability to group actions and only running a specific group.

For instance I would often have a grunt/gulp command to copy specific files into a directory (not related to the project). I would do this as a quick way to move a JS library that was a separate project into a main project while developing.

grunt copy:myproject for instance would basically move all the dist files into my other project as if I was doing a "bower update".

Or the ability to only run the JS files but not the CSS files.

I'm not sure I completely understand the advantages of Mix over Elixir yet.

mikepmtl started a new conversation MIX: How Can I Run Only Running A Subset Of My Webpack.mix.js File

Inside my webpack.mix.js file, I am compiling bootstrap with my custom variables. However, this is very rarely changed. Is there a way to define subcommands in webpack.mix.js?

So perhaps something like:

npm run dev:css npm run dev:bootstrap

and it would only compile a specified group of css?