connecteev

connecteev

Member Since 5 Years Ago

Experience Points
12,570
Total
Experience

2,430 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
93
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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.

Level 3
12,570 XP
May
24
20 hours ago
Activity icon

Replied to Seeing Puzzling And Inconsistent Results With Unit Test

Update: In case you're curious, the env variables are accessible from the unit test. I'm not sure why there's this inconsistency or how to fix this. Any ideas?

Activity icon

Started a new Conversation Seeing Puzzling And Inconsistent Results With Unit Test

Method 1: directly call Laravel Cashier's API to create a new subscription

$user->newSubscription(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'), env('STRIPE_ID_PLAN_1'))->create($paymentMethodId);

$isUserSubscribed = $user->subscribed(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'));

This returns $isUserSubscribed = TRUE.

Method 2: My unit test makes an API call to my API endpoint at /api/v1/me/payments/createOrUpdateSubscription:

        $response = $this->actingAs($user, 'api')->json('PUT', '/api/v1/me/payments/createOrUpdateSubscription', [
            'stripePlanId' => env('STRIPE_ID_PLAN_1'),
            'paymentMethodId' => $paymentMethodId
        ]);

The API endpoint does this (which is exactly the same as what method #1 does directly)

        $loggedinUser = auth()->user();
        $loggedinUser->newSubscription(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'), $stripePlanId)->create($paymentMethodId);

$isUserSubscribed = $user->subscribed(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'));

This returns $isUserSubscribed = FALSE.

Whyy??

May
19
5 days ago
Activity icon

Started a new Conversation Calling Stripe's Javascript APIs From PHPUnit?

This may come off as a strange question, is there a way to call a javascript API from phpunit or laravel dusk? I need to call Stripe's Javascript API: https://stripe.com/docs/js/setup_intents/confirm_card_setup and I don't see a "php" or backend way of doing it

I have a value for this.stripePublicKey and intentToken available in phpunit, I now need to do this:

      this.stripe = Stripe(this.stripePublicKey);
      this.elements = this.stripe.elements();
      this.card = this.elements.create('card', {style: this.stripeOptions.style});
      this.card.mount('#card-element');

      this.stripe.confirmCardSetup(
        this.intentToken.client_secret, {
          payment_method: {
            card: this.card,
            billing_details: {
              name: this.name
            }
          }
        }
      ).then(function(result) {
          console.log("Your card has been added to your account, but you have not yet been charged");
          this.savePaymentMethod(result.setupIntent.payment_method);
      }.bind(this));

Activity icon

Replied to Factory Error On Calling $user->roles()->sync(1) From Unit Test

Not very elegant but this seems to work: https://stackoverflow.com/a/17727695/11491070

No idea what triggers the error though!

Activity icon

Started a new Conversation Factory Error On Calling $user->roles()->sync(1) From Unit Test

I'm seeing a weird error when I try to create my first unit test to create a user and call sync()

class PaymentsAndSubscriptionsTest extends TestCase
{
    // use RefreshDatabase; // cleans out the entire database

    public function setUp(): void
    {
        parent::setUp();
    }

    public function tearDown(): void
    {
        // parent::tearDown();
    }

    /**
     * Can do something
     * @test
     */
    public function can_do_something2()
    {
        $user = $this->create('User', [], false);
        $user->roles()->sync(1); // make sure the new user created has their 'role' set, otherwise we'll get a 403 unauthorized response
    }

Error:

phpunit
PHPUnit 8.5.3 by Sebastian Bergmann and contributors.

....S..EPHP Fatal error:  Cannot redeclare createUnique() (previously declared in /kb_backend_apis_laravel/database/factories/ReactionFactory.php:41) in /kb_backend_apis_laravel/database/factories/ReactionFactory.php on line 41
PHP Fatal error:  Uncaught Illuminate\Contracts\Container\BindingResolutionException: Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable. in /kb_backend_apis_laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php:1011

this is the factory where it's coming from, except I'm not calling it from my unit test...

$factory->state(Reaction::class, 'to_posts', function (Faker $faker) {
    return createUnique($faker, "Post");
});

$factory->state(Reaction::class, 'to_comments', function (Faker $faker) {
    return createUnique($faker, "Comment");
});

// $entityType: Post | Comment
function createUnique(Faker $faker, $entityType)
{
...
}

Any ideas?

May
18
6 days ago
Activity icon

Replied to Finding A Unique Record (based On A Composite Key) In Eloquent

@spyworld thanks but my User table or Reaction table isn't empty, so this doesnt solve my problem. I basically need an eloquent query that does this:

Find the first (or a random) row in the reactions table for which the combination of reactable_id + user_id does NOT exist.

May
17
1 week ago
Activity icon

Replied to Access 2 Values From .env In Phpunit.xml (without A New .env.testing File)

@click thanks for the tips, appreciate you responding. The maintenance burden comes from updating the .env.testing file for local, dev, staging, production with every addition of an env variable... I have these .env files for these environments and it's already starting to get unweildy..

Activity icon

Started a new Conversation Finding A Unique Record (based On A Composite Key) In Eloquent

I have 3 tables: users, posts, reactions...they're self-explanatory. A user can react to (like) a post, so the reactions table contains: id, user_id, post_id. I have a unique DB constraint for: user_id, post_id, ie a specific user can only react to a given post ONCE.

I am trying to create a seeder (using factories) to generate 1000 random reactions using a factory. Here's my old code, which doesn't work.

$factory->define(Reaction::class, function (Faker $faker) {
    $isRemoved = $faker->boolean(10); // parameter = chance of being true
    return [
        'is_archived' => $isRemoved,
        'deleted_at' => $isRemoved ? now() : NULL,
    ];
});

$factory->state(Reaction::class, 'to_posts', function (Faker $faker) {
    $randomPost = Post::inRandomOrder()->first();
    $reactableId = $randomPost['id'];
    $reactableType = 'App\Post';
    $randomUserId = getUniqueUserId($reactableType, $reactableId); 
    return [
        'user_id' => $randomUserId,
        'reactable_type' => $reactableType, // type of entity this reaction was made to
        'reactable_id' => $reactableId, // id of entity this reaction was made to
        'created_at' => null,
        'updated_at' =>  null,
    ];
});


// Get a random User ID, to avoid the unique constraints on the reactions table
// The combination of user_id, reactable_type, reactable_id have to be unique
function getUniqueUserId($reactableType, $reactableId)
{
    $usersThatHaveReactedToThis =
        Reaction::where([
            ['reactable_type', '=', $reactableType],
            ['reactable_id', '=', $reactableId],
        ])
        ->pluck('user_id')
        ->toArray();

    $randomUser =
        User::whereNotIn('id', $usersThatHaveReactedToThis)
        ->inRandomOrder()
        ->first();

    if (!$randomUser) {
        echo "Exiting Seeder: No random User could be found in the DB\n";
        exit;
    }

    $user_id = $randomUser->id;
    return $user_id;
}

Schema:

CREATE TABLE `reactions` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `is_archived` tinyint(1) DEFAULT '0',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  `user_id` int unsigned NOT NULL,
  `reactable_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `reactable_id` int unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_fk_1390101` (`user_id`),
  CONSTRAINT `user_fk_1390101` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=401 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

As you can see, it first tries to get a random post, then it tries to find a user that has not reacted to the post. which is not the same logic as what I am trying to do now. This sucks because it's doing it serially like this, it cannot find UNIQUE values (I have a unique DB constraint for: user_id, post_id, ie a specific user can only react to a given post ONCE, which makes sense) With this, my seeder dies because of "conflicts".

Seeding: ReactionsFakeDataSeeder
Seeding Reactions... 
Exiting Seeder: No random User could be found in the DB

So, it couldnt find a random user that has not reacted to this post - doesnt mean that another random user that has not reacted to a different post does not exist.

My logic above is flawed. A better way would be to write an eloquent query to get any random user than has NOT reacted to any post. What is the best way to go about doing this?

Activity icon

Replied to Access 2 Values From .env In Phpunit.xml (without A New .env.testing File)

@michaloravec it's an interesting idea, but it doesn't quite work..

config/database.php:

        'testing' => [
            'driver' => env('DB_DRIVER_PHPUNIT'),
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_PHPUNIT'),
            'username' => env('DB_USERNAME_PHPUNIT'),
            'password' => env('DB_PASSWORD_PHPUNIT'),
        ],

.env file:


DB_CONNECTION_PHPUNIT=testing
DB_DRIVER_PHPUNIT=mysql
DB_DATABASE_PHPUNIT=my_laravel_testing_db
DB_USERNAME_PHPUNIT=root
DB_PASSWORD_PHPUNIT=root

phpunit.xml:


    <php>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="DB_CONNECTION" value="testing"/>
        <server name="MAIL_MAILER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
    </php>

This is what I have in my Feature/Api/PostsApiTest.php:


<?php
// See more sample TDD / Unit Test code in /Users/kunalpunjabi/Code/KEENBRAIN_NUXT/TDD/devlob_apis_in_laravel_using_tdd/tests/Feature/Http/Controllers/

namespace Tests\Feature\Api;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;

use Tests\TestCase;
use App\User;
use Symfony\Component\HttpFoundation\Response;

class PostsApiTest extends TestCase
{
    use RefreshDatabase; // cleans out the entire database

    public function setUp(): void
    {
        // parent::setUp();
        // $this->artisan('passport:install');
    }

    public function tearDown(): void
    {
        // parent::tearDown();
    }


    /**
     * Can do something
     * @test
     */
    public function can_do_something()
    {
        $user = \App\User::find(['id' => 1]);
        $this->assertTrue($user->email == "[email protected]");
    }

This is the error I see on running phpunit:

There was 1 error:

1) Tests\Feature\Api\PostsApiTest::can_do_something
Error: Call to a member function connection() on null


Activity icon

Replied to Access 2 Values From .env In Phpunit.xml (without A New .env.testing File)

@click I dont think you're understanding the question.

<server name="DB_DATABASE" value="abc" />

works fine.

I am trying to get 'value' of DB_DATABASE from a DIFFERENT .env variable that I have defined in my .env file, called DB_DATABASE_PHPUNIT.

The idea is that I can't have different versions of my phpunit.xml file on dev/staging/production. So I am trying to read from my .env file - is this possible? I really would like to avoid a new .env.testing file - it becomes a maintenance burden.

Activity icon

Started a new Conversation Access 2 Values From .env In Phpunit.xml (without A New .env.testing File)

I am trying to ** read ** values from my .env file and access them in phpunit.xml Is there a way to do this? I do not want to define a new .env.testing file and have to maintain it separately, I just want to override 2 variables in my .env file.

I have tried:

        <server name="DB_CONNECTION" value="config('DB_CONNECTION_PHPUNIT')"/>
        <server name="DB_CONNECTION" value="env('DB_CONNECTION_PHPUNIT')"/>

phpunit errors out with:

4) Tests\Feature\Api\PostsApiTest::non_authenticated_users_cannot_access_the_following_endpoints_for_the_posts_api
InvalidArgumentException: Database connection [env('DB_CONNECTION_PHPUNIT')] not configured.

Any way to do this?

Activity icon

Replied to Phpunit.xml Not Being Read, Using Variables From .env

I am trying to ** read ** values from my .env file and access them in phpunit.xml Is there a way to do this? I do not want to define a new .env.testing file and have to maintain it separately, I just want to override 2 variables in my .env file.

I have tried:

        <server name="DB_CONNECTION" value="config('DB_CONNECTION_PHPUNIT')"/>
        <server name="DB_CONNECTION" value="env('DB_CONNECTION_PHPUNIT')"/>

phpunit errors out with:

4) Tests\Feature\Api\PostsApiTest::non_authenticated_users_cannot_access_the_following_endpoints_for_the_posts_api
InvalidArgumentException: Database connection [env('DB_CONNECTION_PHPUNIT')] not configured.

Any way to do this?

May
16
1 week ago
Activity icon

Commented on Automatically Resolve Dependencies

Not sure if this is the right place to ask, but the topic seems appropriate.

Deployingmy laravel app to ubuntu and I'm really stumped why it wont work. The logs show something that might be related to the service container:

2020/05/16 00:26:07 [error] 2056#2056: *5023 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught ReflectionException: Class translator does not exist in /home/domains/apistaging.mydomain.com/public/current/vendor/laravel/framework/src/Illuminate/Container/Container.php:805
Stack trace:
#0 /home/domains/apistaging.mydomain.com/public/current/vendor/laravel/framework/src/Illuminate/Container/Container.php(805): ReflectionClass->__construct('translator')
#1 /home/domains/apistaging.mydomain.com/public/current/vendor/laravel/framework/src/Illuminate/Container/Container.php(687): Illuminate\Container\Container->build('translator')
#2 /home/domains/apistaging.mydomain.com/public/current/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(796): Illuminate\Container\Container->resolve('translator', Array, true)
#3 /home/domains/apistaging.mydomain.com/public/current/vendor/laravel/framework/src/Illuminate/Container/Container.php(633): Illuminate\Foundation\Application->resolve('translator', Array)
#4 /home/domains/apistaging.mydomain.com/pu...PHP message: PHP Fatal error:  Uncaught ReflectionException: Class translator does not exist in /home/domains/apistaging.mydomain.com/public/current/vendor$

Anyone seen this? This tip didnt help either https://stackoverflow.com/questions/45506239/reflectionexception-class-translator-does-not-exists

Activity icon

Awarded Best Reply on Nginx Config Causes "Primary Script Unknown"

Turns out the fix for this was simple. I had pm2 running, causing a conflicting port

For future reference, if anyone encounters this same issue, run:

pm2 stop all

sudo fuser -k 443/tcp (finds processes using files or socket (in this case TCP port 443) and KILLS them using the -k attribute)

and try a restart again:
sudo service nginx restart
Activity icon

Replied to Nginx Config Causes "Primary Script Unknown"

Turns out the fix for this was simple. I had pm2 running, causing a conflicting port

For future reference, if anyone encounters this same issue, run:

pm2 stop all

sudo fuser -k 443/tcp (finds processes using files or socket (in this case TCP port 443) and KILLS them using the -k attribute)

and try a restart again:
sudo service nginx restart
Activity icon

Started a new Conversation Nginx Config Causes "Primary Script Unknown"

I am having a really puzzling issue with my nginx config. I keep seeing this error:

FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream
client: 76.14.172.29, server: apistaging.mydomain.com, request: 
"GET / HTTP/2.0", upstream: "fastcgi://unix:/var/run/php/php7.4-fpm.sock:", host: "apistaging.mydomain.com"

I did try the suggestions in this question and also this one but nothing has worked. I am asking as a separate question in the hope that someone can help me out (after 2 days stuck on this).

This is my nginx/sites/available/apistaging.mydomain.com.conf file:

server {
        server_name apistaging.mydomain.com;

        # make sure you point to a laravel or wordpress public directory containing an index.php file
        root /home/domains/apistaging.mydomain.com/public/current/public;

        # From https://www.linode.com/docs/web-servers/nginx/slightly-more-advanced-configurations-for-nginx/#host-multiple-websites
        # This link may be outdated. adding 'main' and 'error' makes nginx crap out
        #access_log   /home/domains/apistaging.mydomain.com/log/apistaging.mydomain.access.log;
        error_log   /home/domains/apistaging.mydomain.com/log/apistaging.mydomain.error.log;

        # from https://www.linode.com/docs/web-servers/nginx/slightly-more-advanced-configurations-for-nginx/#limit-or-disable-content-embedding
        add_header X-Frame-Options "SAMEORIGIN";

        # from https://www.linode.com/docs/web-servers/nginx/slightly-more-advanced-configurations-for-nginx/#cross-site-scripting-xss-filter
        add_header X-XSS-Protection "1; mode=block";

        # from https://www.linode.com/docs/web-servers/nginx/slightly-more-advanced-configurations-for-nginx/#disable-content-sniffing
        add_header X-Content-Type-Options "nosniff";

        index index.html index.htm index.php;

        charset utf-8;

        location / {
                try_files $uri $uri/ /index.php?$query_string;
        }

        location = /favicon.ico { access_log off; log_not_found off; }
        location = /robots.txt  { access_log off; log_not_found off; }

        #error_page 404 /index.php;
        # create a custom 404 nginx page, from https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-to-use-custom-error-pages-on-ubuntu-14-04
        error_page 404 /custom_404.html;
        location = /custom_404.html {
            root /etc/nginx/sites-available/custom_nginx_error_pages;
            internal;
        }

        location ~ \.php$ {
                # After installation of php-fpm, check in /var/run/php/ for a fpm sock file like: /var/run/php/php7.3-fpm.sock
                fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }

        location ~ /\.(?!well-known).* {
                deny all;
        }

        # From https://www.linode.com/docs/web-servers/nginx/nginx-installation-and-basic-setup/#static-content-compression
        # Note that gzip has security vulnerabilities and it used to be off by default in the base nginx.conf file (oddly it is set to on by default now)
        # Make sure that gzip is set / enabled only in server{} blocks for individual site configs, not globally in nginx.conf.
        # Though gzip directives can go in the http block if you want it to apply to all sites served by NGINX, it’s safer to use it only inside server blocks for individual sites and content types
        gzip on;
        gzip_types text/plain text/css image/* application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        #listen 443 ssl http2 ipv6only=on; # managed by Certbot (not sure if we support ipv6 yet)
        listen 443 ssl http2; # managed by Certbot, modified to add http2

        #Install SSL certificates and configure https:// on a per-domain-basis by running:
        #sudo certbot --nginx
        #(when prompted, be sure to select the option to set up redirects from http to https and effectively "disable" http)

        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/apistaging.mydomain.com-0002/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/apistaging.mydomain.com-0002/privkey.pem; # managed by Certbot

}

server {
    server_name apistaging.mydomain.com;

    if ($host = apistaging.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    return 404; # managed by Certbot
}

Any help is appreciated.

Activity icon

Replied to Configuring PHPUnit To Connect With A Test DB

@imre08 yes, that works.

What is a good way to fill the DB tables before phpunit runs, and clear them after?

Activity icon

Replied to Configuring PHPUnit To Connect With A Test DB

@tray2 I cant use sqlite, my DB is way too complex and I need to perform complex operations in the tests.

I also need to use .env.testing, but it looks like the phpunit.xml file takes precedence.

May
15
1 week ago
Activity icon

Started a new Conversation Configuring PHPUnit To Connect With A Test DB

Here's what I'd like to do..

  • have a test DB in MySQL (backend_apis_laravel_testing) that gets used for all PhpUnit tests. I do not want to use Sqlite (because I don't know how to view the database and tables in sqlite)
  • clear any cache (if needed) before PHPUnit runs
  • migrate the DB (and seeds) before PHPUnit runs, and cleanup after
  • ignore all settings in phpunit.xml, and only use the .env.testing file (not sure what takes precedence - the .env.testing file, or the settings in phpunit.xml. I would like my .env.testing file to override the phpunit.xml - for reasons that will take too long to explain, I am not allowed to change the phpunit.xml file.

These are the .env.testing settings I would like to use:

APP_NAME=KB
APP_ENV=testing
APP_KEY=base64:SjuP4OPbjmKHASkC22SFF3HbU+p6K22Pi+YkPsxIIwU=
APP_DEBUG=true
APP_URL=http://localhost:8000
FRONTEND_CLIENT_URL=http://localhost:3000

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=backend_apis_laravel_testing
DB_USERNAME=root
DB_PASSWORD=root

And yet, running phpunit keeps using phpunit.xml's settings (and connecting to sqlite, which I don't want). I also don't know how to do the DB migration setup / teardown (and cache clearing) in Laravel 7. Tips appreciated.

May
14
1 week ago
Activity icon

Started a new Conversation Laravel Cashier's Invoices(), UpcomingInvoice() And InvoicesIncludingPending() Return No Data

Even though $loggedinUser is a Billable model and belongs to a user with an active (monthly) subscription plan (subscribed() returns true and I can access this customer's subscription), calling invoicesIncludingPending(), upcomingInvoice() or invoices() on it returns no data.

            $loggedinUser = auth()->user();
            $upcomingInvoice = $loggedinUser->invoicesIncludingPending();
            $upcomingInvoice = $loggedinUser->upcomingInvoice();
            $upcomingInvoice = $loggedinUser->invoices();
            return response([
                "upcoming_invoice" => $upcomingInvoice,
            ], Response::HTTP_OK);

This is what I get back:

{
    "upcoming_invoice": [
        {}
    ]
}

Note that on the Stripe dashboard I do see an upcoming invoice 1 month from now: https://www.webpagescreenshot.info/#v2=572v2l6nG

Are any of you seeing this? Is this a bug in Cashier?

What I am trying to do is get the amount the user will be charged at the next billing cycle (note that this may NOT be the same as the subscription plan's price the user is on - they may have a credit applied to their account, etc)

FYI..

  • Cashier Version: 11
  • Laravel Version: 7.x
  • PHP Version: 7.4.5
  • Database Driver & Version: MySQL 8
Activity icon

Replied to Proper Way To Handle Exceptions

@bugsysha thanks for the help

May
13
1 week ago
Activity icon

Awarded Best Reply on Proper Way To Handle Exceptions

Figured it out, basically the signatures weren't matching:

In the controller:

    private function getDefaultPaymentMethodId(User $user)
    {
        try {
            $stripeCustomer = $user->asStripeCustomer();
            $defaultPaymentMethodId = $stripeCustomer->invoice_settings->default_payment_method;
            return $defaultPaymentMethodId;

        } catch (\Exception $e) {
            \Log::emergency('throw MyStripeException');
            throw new \App\Exceptions\MyStripeException($e);
        }
    }

In app\Exceptions\MyStripeException.php:


<?php

namespace App\Exceptions;

use Throwable;
use Exception;
use App\Exceptions\Handler;

class MyStripeException extends Exception
{
    public $exception;

    public function __construct(Exception $e)
    {
        $this->exception = $e;
        parent::__construct($e->getError()->message, $e->getCode(), null);
    }

    /**
     * Report or log an exception.
     *
     * @param  \Throwable  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report()
    {
        $e = $this->exception;
        \Log::emergency('In MyStripeException::report(): ' .
            ' Exception Message is:' . $e->getMessage() .
            ' Status is:' . $e->getHttpStatus() .
            ' Type is:' . $e->getError()->type .
            ' Code is:' . $e->getError()->code .
            ' Param is:' . $e->getError()->param .
            ' Message is:' . $e->getError()->message
        );

        if ($e instanceof \Stripe\Exception\CardException) {
            // Since it's a decline, \Stripe\Exception\CardException will be caught
            \Log::emergency("Since it's a decline, \Stripe\Exception\CardException will be caught");

        } else if ($e instanceof \Stripe\Exception\RateLimitException) {
            // Too many requests made to the API too quickly
            \Log::emergency("Too many requests made to the API too quickly");
        } else if ($e instanceof \Stripe\Exception\InvalidRequestException) {
            // Invalid parameters were supplied to Stripe's API
            \Log::emergency("Invalid parameters were supplied to Stripe's API");
        } else if ($e instanceof \Stripe\Exception\AuthenticationException) {
            // Authentication with Stripe's API failed
            // (maybe you changed API keys recently)
            \Log::emergency("Authentication with Stripe's API failed (maybe you changed API keys recently)");
        } else if ($e instanceof \Stripe\Exception\ApiConnectionException) {
            // Network communication with Stripe failed
            \Log::emergency("Network communication with Stripe failed");
        } else if ($e instanceof \Stripe\Exception\ApiErrorException) {
            // Display a very generic error to the user, and maybe send
            // yourself an email
            \Log::emergency("Display a very generic error to the user, and maybe send yourself an email");

        } else {
            // Something else happened, completely unrelated to Stripe
            \Log::emergency("Something else happened, completely unrelated to Stripe");
            parent::report($e);
        }
    }
}

Activity icon

Replied to Proper Way To Handle Exceptions

Figured it out, basically the signatures weren't matching:

In the controller:

    private function getDefaultPaymentMethodId(User $user)
    {
        try {
            $stripeCustomer = $user->asStripeCustomer();
            $defaultPaymentMethodId = $stripeCustomer->invoice_settings->default_payment_method;
            return $defaultPaymentMethodId;

        } catch (\Exception $e) {
            \Log::emergency('throw MyStripeException');
            throw new \App\Exceptions\MyStripeException($e);
        }
    }

In app\Exceptions\MyStripeException.php:


<?php

namespace App\Exceptions;

use Throwable;
use Exception;
use App\Exceptions\Handler;

class MyStripeException extends Exception
{
    public $exception;

    public function __construct(Exception $e)
    {
        $this->exception = $e;
        parent::__construct($e->getError()->message, $e->getCode(), null);
    }

    /**
     * Report or log an exception.
     *
     * @param  \Throwable  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report()
    {
        $e = $this->exception;
        \Log::emergency('In MyStripeException::report(): ' .
            ' Exception Message is:' . $e->getMessage() .
            ' Status is:' . $e->getHttpStatus() .
            ' Type is:' . $e->getError()->type .
            ' Code is:' . $e->getError()->code .
            ' Param is:' . $e->getError()->param .
            ' Message is:' . $e->getError()->message
        );

        if ($e instanceof \Stripe\Exception\CardException) {
            // Since it's a decline, \Stripe\Exception\CardException will be caught
            \Log::emergency("Since it's a decline, \Stripe\Exception\CardException will be caught");

        } else if ($e instanceof \Stripe\Exception\RateLimitException) {
            // Too many requests made to the API too quickly
            \Log::emergency("Too many requests made to the API too quickly");
        } else if ($e instanceof \Stripe\Exception\InvalidRequestException) {
            // Invalid parameters were supplied to Stripe's API
            \Log::emergency("Invalid parameters were supplied to Stripe's API");
        } else if ($e instanceof \Stripe\Exception\AuthenticationException) {
            // Authentication with Stripe's API failed
            // (maybe you changed API keys recently)
            \Log::emergency("Authentication with Stripe's API failed (maybe you changed API keys recently)");
        } else if ($e instanceof \Stripe\Exception\ApiConnectionException) {
            // Network communication with Stripe failed
            \Log::emergency("Network communication with Stripe failed");
        } else if ($e instanceof \Stripe\Exception\ApiErrorException) {
            // Display a very generic error to the user, and maybe send
            // yourself an email
            \Log::emergency("Display a very generic error to the user, and maybe send yourself an email");

        } else {
            // Something else happened, completely unrelated to Stripe
            \Log::emergency("Something else happened, completely unrelated to Stripe");
            parent::report($e);
        }
    }
}

Activity icon

Replied to Proper Way To Handle Exceptions

@bugsysha I need the exception data because I need to act on it differently, depending on what the exception thrown by Stripe is. I am trying to centralize all the Stripe exception handling, and Stripe can throw one of many exeptions, like \Stripe\Exception\RateLimitException, \Stripe\Exception\CardException, etc.

I did try using $this and it didn't work:

        try {
            $stripeCustomer = $user->asStripeCustomer();
            $defaultPaymentMethodId = $stripeCustomer->invoice_settings->default_payment_method;
            return $defaultPaymentMethodId;

        } catch (\Exception $e) {
            \Log::emergency('throw MyStripeException');
            throw new \App\Exceptions\MyStripeException(
                "{$e->getError()->message}", $e->getCode(), null
            );
        }

In class MyStripeException:

namespace App\Exceptions;

use Throwable;
use Exception;
use App\Exceptions\Handler;

class MyStripeException extends Exception
{
    // see vendor/laravel//cashier/src/Exceptions/IncompletePayment.php
    public function __construct($message = '', $code = 0, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
    public function report()
    {
        // $e = Handler::prepareException($this);
        // $e = $this;
        \Log::emergency('In MyStripeException::report(): ' .
            $this->getMessage()
            // 'Status is:' . $e->getHttpStatus() .
            // 'Type is:' . $e->getError()->type .
            // 'Code is:' . $e->getError()->code .
            // 'Param is:' . $e->getError()->param .
            // 'Message is:' . $e->getError()->message
        );
   }

This is what I see in the logs:

[2020-05-13 15:12:58] local.EMERGENCY: throw MyStripeException  
[2020-05-13 15:12:58] local.EMERGENCY: In MyStripeException::report(): dude No such customer: dss  
[2020-05-13 15:12:58] local.EMERGENCY: Something else happened, completely unrelated to Stripe  
[2020-05-13 15:12:58] local.ERROR: Call to undefined method Exception::report() {"userId":1,"exception":"[object] (Error(code: 0): Call to undefined method Exception::report() at /app/Exceptions/MyStripeException.php:63)
[stacktrace]
Activity icon

Replied to Proper Way To Handle Exceptions

I also tried


    public function report()
    {
        $e = $this;
...

but had no luck either

Activity icon

Replied to Proper Way To Handle Exceptions

@bugsysha I tried that, here's the problem, I don't know how to access the $exception object in the render() function (so that I can then call $e->getError() etc, and the docs dont give an example how to do it.

Here's what I've tried:


<?php

namespace App\Exceptions;

use Throwable;
use Exception;
use App\Exceptions\Handler;

class MyStripeException extends Exception
{
    public function __construct($message = '', $code = 0, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }


    public function report(Exception $e)
    {
        // $e = $this;
        \Log::emergency('In MyStripeException::report(): ' .
            // 'Status is:' . $e->getHttpStatus() .
            'Type is:' . $e->getError()->type .
            'Code is:' . $e->getError()->code .
            'Param is:' . $e->getError()->param .
            'Message is:' . $e->getError()->message
        );

This is what I see in the logs:

[2020-05-13 14:27:34] local.EMERGENCY: throw MyStripeException  
[2020-05-13 14:27:34] local.ERROR: Unresolvable dependency resolving [Parameter #0 [ <optional> $message ]] in class Exception {"userId":1,"exception":"[object] (Illuminate\Contracts\Container\BindingResolutionException(code: 0): Unresolvable dependency resolving [Parameter #0 [ <optional> $message ]] in class Exception at /app/vendor/laravel/framework/src/Illuminate/Container/Container.php:1026)
[stacktrace]
#0 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(939): Illuminate\Container\Container->unresolvablePrimitive(Object(ReflectionParameter))
#1 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(874): Illuminate\Container\Container->resolvePrimitive(Object(ReflectionParameter))
#2 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(836): Illuminate\Container\Container->resolveDependencies(Array)
#3 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(687): Illuminate\Container\Container->build('Exception')
Activity icon

Started a new Conversation Proper Way To Handle Exceptions

What I am trying to do is build a Stripe-specific exception class to handle any Stripe-related exception:

        try {
            $stripeCustomer = $user->asStripeCustomer();
            $defaultPaymentMethodId = $stripeCustomer->invoice_settings->default_payment_method;
            return $defaultPaymentMethodId;

        } catch(\Stripe\Exception\CardException $e) {
            // Since it's a decline, \Stripe\Exception\CardException will be caught
            echo 'Status is:' . $e->getHttpStatus() . '\n';
            echo 'Type is:' . $e->getError()->type . '\n';
            echo 'Code is:' . $e->getError()->code . '\n';
            // param is '' in this case
            echo 'Param is:' . $e->getError()->param . '\n';
            echo 'Message is:' . $e->getError()->message . '\n';
        } catch (\Stripe\Exception\RateLimitException $e) {
            // Too many requests made to the API too quickly
        } catch (\Stripe\Exception\InvalidRequestException $e) {
            // Invalid parameters were supplied to Stripe's API
        } catch (\Stripe\Exception\AuthenticationException $e) {
            // Authentication with Stripe's API failed
            // (maybe you changed API keys recently)
        } catch (\Stripe\Exception\ApiConnectionException $e) {
            // Network communication with Stripe failed
        } catch (\Stripe\Exception\ApiErrorException $e) {
            // Display a very generic error to the user, and maybe send
            // yourself an email
        } catch (\Exception $e) {
            // Something else happened, completely unrelated to Stripe
            return [false, '$e->getError()->message', null];
        }

I would like to move all this exception logic (for Stripe) from my Controller above into an exception class.

What is the correct (Laravel) way to handle exceptions? How would you do it?

Some context:

When Laravel 7.x came out, according to the upgrade guide I believe there was a symfony-related update on how exceptions were handled.

Not sure if the php artisan make:exception command has been updated, but running php artisan make:exception MyStripeException generates a file like this

<?php

namespace App\Exceptions;

use Exception;

class MyStripeException extends Exception
{
    //
}

However, if you look at app\Exceptions\Handler.php it looks more like this


<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Throwable  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        return parent::render($request, $exception);
    }
}

Confused how to proceed - how would you build the exception class for Stripe?

Activity icon

Replied to Implementing A "Forever" Plan In Stripe (like Laracasts)

@bobbybouwmann thanks for sharing your thoughts...all of that makes sense.

Prorating when you upgrade from monthly -> forever: Stripe does support prorations, and Cashier does it by default, too. I plan on doing this.

Re: Downgrading and Canceling:

  • Can you downgrade from Yearly to Monthly? Stripe gives you a "credit" back, but you dont get your money back....you "spend" the credit every month. The balance will decrease the amount due on the customer's next invoice.

  • Can you cancel a Yearly plan? What happens? Stripe doesnt offer refunds, and any money you've paid is "lost" (unless you resume your subscription)

  • Can you cancel a Forever plan? What happens? You can't give a prorated credit back here - because you were being billed "forever". Can't see what Stripe does here because it doesn't offer a "forever" subscription plan. You are suggesting not allowing it at all, which may be the most logical thing to do. I'd like to know...Does Laracasts allow you to downgrade from Forever to Monthly / Yearly?

Thanks..

Activity icon

Started a new Conversation Implementing A "Forever" Plan In Stripe (like Laracasts)

Just like Laracasts, I am trying to implement a "Forever" Subscription plan in Stripe.

I have 2 questions:

  1. This is for anyone with knowledge about plan upgrades, downgrades and prorations. How would this work, if you were upgrading / downgrading from a monthly plan to the "forever" plan? I know Stripe takes care of prorations for you, but should downgrading from the "forever" plan be allowed? If so, how would the charges work?

  2. For anyone that has a "forever" subscription plan, does Laracasts allow you to downgrade (if you try)? I'm not trying to trick you into downgrading - I'm genuinely curious.

May
12
1 week ago
Activity icon

Started a new Conversation Fixing The Timezone For Datetime Fields

When I add a new record to MySQL, the created_at and updated_at fields are always 7 hours ahead of my current timezone (I am on PST or Pacific time).

I did try a SELECT NOW() in MySQL and it returns my current time (PST), however anytime my Laravel application adds a record, the created_at and updated_at fields (or any other dates) end up being 7 hours ahead.

What gives??

Activity icon

Awarded Best Reply on Stripe Webhooks Using Laravel Cashier And Spatie/laravel-stripe-webhooks

Here's the answer for anyone looking:

  1. To disable cashier's routes: Add Cashier::ignoreRoutes(); in the boot method of your AppServiceProvider

  2. To fix the 500 error: When trying to override the Stripe Webhook job to perform custom logic as specified in https://github.com/spatie/laravel-stripe-webhooks#performing-custom-logic Use

use Spatie\StripeWebhooks\ProcessStripeWebhookJob;

class MyCustomStripeWebhookJob extends ProcessStripeWebhookJob
{
    public function handle()
    {
        // do some custom stuff beforehand

        parent::handle();

        // do some custom stuff afterwards
    }
}

You cannot have a __construct() function (which gets created by default if you run php artisan make:job) in this job, which will throw the 500 exception

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

Exception:

[2020-05-12 17:08:26] local.ERROR: Typed property Spatie\WebhookClient\ProcessWebhookJob::$webhookCall must not be accessed before initialization {"exception":"[object] (Error(code: 0): Typed property Spatie\WebhookClient\ProcessWebhookJob::$webhookCall must not be accessed before initialization at 
Activity icon

Replied to Stripe Webhooks Using Laravel Cashier And Spatie/laravel-stripe-webhooks

Here's the answer for anyone looking:

  1. To disable cashier's routes: Add Cashier::ignoreRoutes(); in the boot method of your AppServiceProvider

  2. To fix the 500 error: When trying to override the Stripe Webhook job to perform custom logic as specified in https://github.com/spatie/laravel-stripe-webhooks#performing-custom-logic Use

use Spatie\StripeWebhooks\ProcessStripeWebhookJob;

class MyCustomStripeWebhookJob extends ProcessStripeWebhookJob
{
    public function handle()
    {
        // do some custom stuff beforehand

        parent::handle();

        // do some custom stuff afterwards
    }
}

You cannot have a __construct() function (which gets created by default if you run php artisan make:job) in this job, which will throw the 500 exception

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

Exception:

[2020-05-12 17:08:26] local.ERROR: Typed property Spatie\WebhookClient\ProcessWebhookJob::$webhookCall must not be accessed before initialization {"exception":"[object] (Error(code: 0): Typed property Spatie\WebhookClient\ProcessWebhookJob::$webhookCall must not be accessed before initialization at 
Activity icon

Started a new Conversation Stripe Webhooks Using Laravel Cashier And Spatie/laravel-stripe-webhooks

Really stuck on this and hope someone's able to help me out!

I'm using Laravel Cashier and just installed https://github.com/spatie/laravel-stripe-webhooks - I'd like to use it to listen to and respond to webhook events from Stripe.

I have 2 problems / questions:

  1. Once you set the webhooks URL, how do you disable the default Cashier URL of /stripe/webhook?

According to the installation steps, you define your webhook APi endpoint like this:

In routes/web.php:

Route::stripeWebhooks('my_stripe_webhooks_endpoint');

In the VerifyCsrfToken middleware:

protected $except = [
    'my_stripe_webhooks_endpoint',
];

Now, when I use the stripe-cli (on localhost) and run stripe listen (and forward events to http://localhost:8000/my_stripe_webhooks_endpoint, as specified in the Stripe docs, I see a 500 POST response. Why, and how do i turn it to a 200 response that Stripe needs to see?

^COneStepAtATime:kb_backend_apis_laravel$ stripe listen --forward-to http://localhost:8000/my_stripe_webhooks_endpoint
> Ready! Your webhook signing secret is whsec_ER94Uk56z5nlcKrD1OREbX2Q9e1LgEXg (^C to quit)
2020-05-11 17:33:48   --> payment_intent.created [evt_0Ghm46DXGF9cqh5pIZatClX2]
2020-05-11 17:33:48  <--  [500] POST http://localhost:8000/my_stripe_webhooks_endpoint [evt_0Ghm46DXGF9cqh5pIZatClX2]
2020-05-11 17:35:58   --> payment_intent.created [evt_0Ghm6DDXGF9cqh5pdW88RL1W]
2020-05-11 17:35:58  <--  [500] POST http://localhost:8000/my_stripe_webhooks_endpoint [evt_0Ghm6DDXGF9cqh5pdW88RL1W]

On the other hand, this (Default) Cashier webhook route: stripe/webhook is still enabled, and responds with a 200 status code! Logs below from performing the same operation, except I forward the webhook events to /stripe/webhook:

Which brings me to question #2:

2 How can I disable this default Cashier route, and make the one I want to use return a 200 response?

^COneStepAtATime:kb_backend_apis_laravel $ stripe listen --forward-to http://localhost:8000/stripe/webhook
> Ready! Your webhook signing secret is whsec_Ex94Uk56z5nlcKrD1OREbXVQ9e1LgEXg (^C to quit)
2020-05-11 17:51:46   --> payment_method.attached [evt_0GhmLTDXGF9cqh5p67406apI]
2020-05-11 17:51:46  <--  [200] POST http://localhost:8000/stripe/webhook [evt_0GhmLTDXGF9cqh5p67406apI]
2020-05-11 17:51:50   --> customer.source.created [evt_0GhmLTDXGF9cqh5pUVdieeIT]
2020-05-11 17:51:50  <--  [200] POST http://localhost:8000/stripe/webhook [evt_0GhmLTDXGF9cqh5pUVdieeIT]

May
10
2 weeks ago
Activity icon

Replied to Implementing A Simple Animated Checkbox On Click (like Laracasts)?

@denniseilander thank you, this is awesome! I have the animation working, now I just have to trigger the javascript at the right times. When I tried it I was missing the @ keyframes css - thanks!

Activity icon

Replied to Implementing A Simple Animated Checkbox On Click (like Laracasts)?

@MichalOravec thanks to your response to my other thread, there's some bug on that discussion thread that prevented me as an author from replying to you. I dont need a switch UI, but something like the gif above...but I still appreciate it!

Activity icon

Started a new Conversation Implementing A Simple Animated Checkbox On Click (like Laracasts)?

I am trying to implement a simple animated checkbox on click, like the Laracasts subscription page

Gif of what it looks like: https://recordit.co/3QdR4RP7dR

I like this animation (beats radio buttons) and am looking to add "delight" to my app, and so I need some base code to start from. Any links or pointers?

Activity icon

Started a new Conversation Implementing A Simple Animated Checkbox On Click (like Laracasts)?

I am trying to implement a simple animated checkbox like Laracasts...gif below. Any pointers on where I can get the code for something like this (just looking for a base so I can modify)?

Animated checkbox></p>

                    </div>
                </div>
                    </div>
    </div>
    <div class=

May
03
3 weeks ago
Activity icon

Awarded Best Reply on Cannot Run 'npm Run Dev' When Using LOCAL Package For Development

Here's the fix:

Update webpack.mix.js with the correct path in path.resolve

    .webpackConfig({
        resolve: {
            modules: [
                path.resolve(__dirname, '_PACKAGE_FOR_LOCAL_DEVELOPMENT/localPkg/resources/assets/js'),
                'node_modules'
            ],
            alias: {
                'vue$': mix.inProduction() ? 'vue/dist/vue.min' : 'vue/dist/vue.js'
            }
        }
    });

Activity icon

Replied to Cannot Run 'npm Run Dev' When Using LOCAL Package For Development

Here's the fix:

Update webpack.mix.js with the correct path in path.resolve

    .webpackConfig({
        resolve: {
            modules: [
                path.resolve(__dirname, '_PACKAGE_FOR_LOCAL_DEVELOPMENT/localPkg/resources/assets/js'),
                'node_modules'
            ],
            alias: {
                'vue$': mix.inProduction() ? 'vue/dist/vue.min' : 'vue/dist/vue.js'
            }
        }
    });

Activity icon

Replied to Cannot Run 'npm Run Dev' When Using LOCAL Package For Development

I've been stuck on this problem for a while, so if you've managed to get npm working with local packages, please let me know!

Activity icon

Replied to Implement Stripe Subscriptions With Laravel Cashier

@bugsysha I have, but couldnt find one that was relevant. I am thinking about Laravel Spark now :(

Activity icon

Started a new Conversation Cannot Run 'npm Run Dev' When Using LOCAL Package For Development

I am using a package LOCALLY for development, but am unable to get npm to "find" the libraries in my local package. As a result, npm run dev errors out.

For some context, this is what I have added to composer.json:

    "require": {
        ...
        "myPackage": "~9.0",
        ...
    },
    ...
    ...
    ...

    "repositories": {
        "local": {
            "type": "path",
            "url": "./_PACKAGE_FOR_LOCAL_DEVELOPMENT/my_local_package/"
        }
    }

This works fine when I run composer update, and the package is able to be found.

However, npm poses a challenge.

After successfully running npm install, there's an issue with running npm run dev

when I run npm run dev I see errors:

ERROR  Failed to compile with 46 errors
2:31:18 PM

These dependencies were not found:

my-bootstrap in ./resources/js/my-bootstrap.js
auth/authBase in ./resources/js/app.js

In my resources/js/app.js I have;

require('my-bootstrap');
var authBase = require('auth/authBase');

and I need it to be able to find and reference

./_PACKAGE_FOR_LOCAL_DEVELOPMENT/resources/assets/js/my-bootstrap.js
./_PACKAGE_FOR_LOCAL_DEVELOPMENT/resources/assets/js/auth/authBase.js

etc

I did Google around with no luck. None of these helped: https://github.com/JeffreyWay/laravel-mix/issues/990

I suspect it's some setting I need to add in my default Webpack / Laravel Mix config (webpack.mix.js) that gets installed with Laravel.

Any ideas how to fix this? I need to tell npm to reference the libraries from my local package. Thanks.

Apr
22
1 month ago
Activity icon

Replied to Refresh For Laracasts Series For "How To Accept Payments" With Stripe

@bobbybouwmann sounds good, thank you!

Btw Should I keep this discussion open for Jeffrey Way, since it's filed as a request?