nexxai

DevOps Engineer at Symend

Member Since 2 Years Ago

Experience Points
40,630
Total
Experience

4,370 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
352
Lessons
Completed
Best Reply Awards
4
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 9
40,630 XP
Sep
01
1 month ago
Activity icon

Replied to Passport + Axios: "Unauthenticated."

Yeah sorry, I had upgraded and it solved my problem too, but forgot to mark this as solved. Thanks for sharing and reminding me!

Aug
25
1 month ago
Aug
24
1 month ago
Activity icon

Started a new Conversation Passport + Axios: "Unauthenticated."

I have no idea what I'm doing wrong here.

In my app\Http\Kernel.php, $middlewareGroups, I've got: \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,

I've run php artisan passport:keys --force multiple times.

My app.js has:

window.axios = require('axios').default;
window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content')
};

DevTools shows the laravel_token cookie being sent with the request.

The (snipped) version of the Vue component being run is this:

<script>

const axios = require('axios').default;

export default {
    components: {
        'axios': axios,
    },

    watch: {
                axios.post('/api/photo/reorder', reordered).catch(error => {
                    if (error.response.status === 422) {
                        this.errors = error.response.data.errors || {};
                    }
                });
        }
    }
}

</script>

The route being hit is:

Route::name('api.')->group(function () {
    Route::post('photo/reorder', '[email protected]')
        ->name('photo.reorder')
        ->middleware('auth:api');
});

This is all super simple code; what the heck am I missing here?

Edit: Forgot to mention, this is Laravel 7.25.0

Jul
23
2 months ago
Activity icon

Awarded Best Reply on Git Not Ignoring .gitignore

And if you've added it to your gitignore after it's been committed once, you'll need to do: git rm --cached /vendor and then do a new commit to force the changes.

You can check that you've done it right after by doing git check-ignore -v -- /vendor to ensure that it's now being caught by your new rule (it won't trip before you do the git rm --cached).

Jul
10
3 months ago
Activity icon

Awarded Best Reply on Weird HTML Output When Testing Omnipay

For anyone who finds this code in the future, I replaced the

        if ($response->isRedirect()) {
            $response->redirect();
        }

in the controller with

        if ($response->isRedirect()) {
            return redirect($response->getRedirectUrl());
        }

and it works so that solves that mystery.

Activity icon

Replied to Weird HTML Output When Testing Omnipay

For anyone who finds this code in the future, I replaced the

        if ($response->isRedirect()) {
            $response->redirect();
        }

in the controller with

        if ($response->isRedirect()) {
            return redirect($response->getRedirectUrl());
        }

and it works so that solves that mystery.

Activity icon

Started a new Conversation Weird HTML Output When Testing Omnipay

So I built a cart that uses omnipay and when I run one specific integration test that actually tests the purchase, for some reason, it dumps the HTML output that PayPal returns to the test showing the redirection etc., but not before the test "dots"(?) like a dump() or dd() would and I'm not sure where it's coming from. It's like there's an echo() command somewhere but I'm pretty sure I haven't touched one of those in years.

Example:

➜  project git:(dev) ✗ php -c ../../.php.ini vendor/bin/phpunit --filter an_order_and_its_items_are_created_when_a_valid_checkout_is_made
PHPUnit 8.5.8 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url='https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&amp;useraction=commit&amp;token=EC-XXXXXXXXXXXXXXXXXXXX'" />

        <title>Redirecting to https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&amp;useraction=commit&amp;token=EC-XXXXXXXXXXXXXXXXXXXX</title>
    </head>
    <body>
        Redirecting to <a href="https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&amp;useraction=commit&amp;token=EC-XXXXXXXXXXXXXXXXXXXX">https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&amp;useraction=commit&amp;token=EC-XXXXXXXXXXXXXXXXXXXX</a>.
    </body>
</html>

Time: 3.4 seconds, Memory: 38.50 MB

OK (1 test, 6 assertions)

Paypal.php:

<?php

namespace App;

use Omnipay\Omnipay;

/**
 * Class PayPal.
 */
class PayPal
{
    /**
     * @return mixed
     */
    public function gateway()
    {
        $gateway = Omnipay::create('PayPal_Express');

        $gateway->initialize([
            'username' => config('services.paypal.username'),
            'password' => config('services.paypal.password'),
            'signature' => config('services.paypal.signature'),
            'testMode' => config('services.paypal.sandbox'),
        ]);

        return $gateway;
    }

    /**
     * @param array $parameters
     * @return mixed
     */
    public function purchase(array $parameters)
    {
        return $this->gateway()
            ->purchase($parameters)
            ->send();
    }

    public function complete(array $parameters)
    {
        return $this->gateway()
            ->completePurchase($parameters)
            ->send();
    }

    /**
     * @param $amount
     * @return string
     */
    public function formatAmount($amount)
    {
        return number_format($amount, 2, '.', '');
    }

    /**
     * @param $order
     * @return string
     */
    public function getCancelUrl($order)
    {
        return route('paypal.checkout.cancelled', $order->non_user_identifier);
    }

    /**
     * @param $order
     * @return string
     */
    public function getReturnUrl($order)
    {
        return route('paypal.checkout.completed', $order->non_user_identifier);
    }

    /**
     * @param $order
     * @return string
     */
    public function getNotifyUrl($order)
    {
        $env = config('services.paypal.sandbox') ? 'sandbox' : 'live';

        return route('webhook.paypal.ipn', [$order->non_user_identifier, $env]);
    }
}

PaypalController.php:

<?php

namespace App\Http\Controllers;

use App\Http\Requests\AcceptOrderRequest;
use App\Order;
use App\PayPal;
use Illuminate\Http\Request;

class PayPalController extends Controller
{
    /**
     * @param AcceptOrderRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function checkout(AcceptOrderRequest $request)
    {
        $order = \App\Order::placeOrder($request->validated());

        $paypal = new PayPal();

        $response = $paypal->purchase([
            'amount' => $paypal->formatAmount($order->total),
            'transactionId' => $order->non_user_identifier,
            'currency' => $order->country->paypal_currency_code,
            'cancelUrl' => $paypal->getCancelUrl($order),
            'returnUrl' => $paypal->getReturnUrl($order),
        ]);

        if ($response->isRedirect()) {
            $response->redirect();
        }

        return redirect()->back()->with([
            'message' => $response->getMessage(),
        ]);
    }

The test:

    /** @test */
    public function an_order_and_its_items_are_created_when_a_valid_checkout_is_made()
    {
        $cart = create(Cart::class);
        $cart->addItem($item = make(CartItem::class)->toArray());
        $country = create(Country::class);
        $email = '[email protected]';
        $first = 'John';
        $last = 'Doe';
        $address = '123 Test Street';
        $city = 'New York';
        $state = 'Alabama';
        $zip = '90210';

        $this->assertCount(0, Order::all());
        $this->assertCount(0, OrderItem::all());

        $this->post(route('checkout.payment.paypal'), [
            'cart_id' => encrypt($cart->non_user_identifier),
            'email_address' => $email,
            'first_name' => $first,
            'last_name' => $last,
            'address' => $address,
            'city' => $city,
            'state' => $state,
            'zipcode' => $zip,
            'country_id' => $country->id,
        ]);

        $this->assertDatabaseHas('orders', [
            'email_address' => $email,
            'first_name' => $first,
            'last_name' => $last,
            'address' => $address,
            'city' => $city,
            'state' => $state,
            'zipcode' => $zip,
            'country_id' => $country->id,
            'phone_number' => $phone,
        ])
            ->assertDatabaseHas('order_items', [
                'name' => $item['name'],
                'photo_id' => $item['photo_id'],
                'price' => $item['unit_price'],
                'quantity' => $item['quantity'],
            ]);

        $this->assertCount(1, Order::all());
        $this->assertCount(1, OrderItem::all());
    }
Jul
03
3 months ago
Activity icon

Replied to Database Clone In Real Time

Look into replication and setting up a second DB server using MySQL's built in functionality (https://dev.mysql.com/doc/refman/8.0/en/replication.html)

Jun
29
3 months ago
Activity icon

Replied to Column Not Found In Laravel

Do you have a column titled storefront_facebook_link in the settings table of your database?

Jun
26
3 months ago
Activity icon

Awarded Best Reply on Run 'npm Run Prod' Only If JS/CSS Assets Changed?

For anyone coming here later, this is what I've got so far.

Please note: this will only check the last commit (the HEAD~1 part of the git command; HEAD~2 will check the last two, etc.). This will almost certainly be a problem if you have multiple commits in a single push.

I will update this script for any future searchers if anyone can provide a better way to track files changed between git pulls instead of between git commits, or make any general improvements to this, since my scripting is basically garbage. But it does the trick.

# Dump the list of filenames changed in the last git commit
git diff --name-only HEAD HEAD~1 > /tmp/gitdiff.txt

# Default to no changes
yarn=false

# Read the /tmp/gitdiff.txt file line by line....
while read line; do
    # The regex to search for CSS/JS/Vue/.lock/JSON files
    positiveMatch='^(resources\/|).*(css|js|vue|lock|json)$'

    # The regex to ignore the composer.json files and the entire /public folder
    negativeMatch='^(composer|public)'

    echo $line
    # Check to see if any those filetypes are listed 
    if  [[ $line =~ $positiveMatch && ! $line =~ $negativeMatch ]]; then 
        # ...and if so, set the yarn flag to true
        yarn=true;
    fi
done < /tmp/gitdiff.txt

# If any changes were detected, run the necessary yarn commands
if $yarn ; then
    yarn install --save
    yarn run production
fi

# Cleanup
yarn=false
rm /tmp/gitdiff.txt

CHANGELOG:

  • 06/28/2020 - Fixed the if $yarn line as it was always evaluating to true; updated regex to include package.json and yarn.lock, while excluding composer.json (does not impact yarn usage) and the entire public folder so that it can be recompiled
Activity icon

Replied to Run 'npm Run Prod' Only If JS/CSS Assets Changed?

For anyone coming here later, this is what I've got so far.

Please note: this will only check the last commit (the HEAD~1 part of the git command; HEAD~2 will check the last two, etc.). This will almost certainly be a problem if you have multiple commits in a single push.

I will update this script for any future searchers if anyone can provide a better way to track files changed between git pulls instead of between git commits, or make any general improvements to this, since my scripting is basically garbage. But it does the trick.

# Dump the list of filenames changed in the last git commit
git diff --name-only HEAD HEAD~1 > /tmp/gitdiff.txt

# Default to no changes
yarn=false

# Read the /tmp/gitdiff.txt file line by line....
while read line; do
    # The regex to search for CSS/JS/Vue/.lock/JSON files
    positiveMatch='^(resources\/|).*(css|js|vue|lock|json)$'

    # The regex to ignore the composer.json files and the entire /public folder
    negativeMatch='^(composer|public)'

    echo $line
    # Check to see if any those filetypes are listed 
    if  [[ $line =~ $positiveMatch && ! $line =~ $negativeMatch ]]; then 
        # ...and if so, set the yarn flag to true
        yarn=true;
    fi
done < /tmp/gitdiff.txt

# If any changes were detected, run the necessary yarn commands
if $yarn ; then
    yarn install --save
    yarn run production
fi

# Cleanup
yarn=false
rm /tmp/gitdiff.txt

CHANGELOG:

  • 06/28/2020 - Fixed the if $yarn line as it was always evaluating to true; updated regex to include package.json and yarn.lock, while excluding composer.json (does not impact yarn usage) and the entire public folder so that it can be recompiled
Activity icon

Started a new Conversation Run 'npm Run Prod' Only If JS/CSS Assets Changed?

Ok so running npm run prod takes about 45 seconds on my server, during which time the site is unavailable. This seems like a waste of time if there weren't any new changes to be compiled.

Is there a way in bash to watch which files changed in the last git pull and only run if there were changes to any files in the resources/js or resources/css folders?

Activity icon

Replied to Issue Submitting That I Think Might Be Cookie Mismatch?

One thing you can do is start adding logging (Log::) near where you think the faults are happening so you can dig in deeper to what may (or may not) be happen

Activity icon

Replied to Should Key Be Generated During Image Build?

No, because the key is used for various encryption tasks, so if you change it and redeploy your app, things like existing sessions will immediately become invalid since they won't be decryptable.

Jun
25
3 months ago
Activity icon

Awarded Best Reply on Add Custom Font Laravel 6

If you put the file in /public/fonts/..., that means it's available to the public as /fonts/....

Try updating that location in the src: property and see if that works.

Activity icon

Replied to Add Custom Font Laravel 6

If you put the file in /public/fonts/..., that means it's available to the public as /fonts/....

Try updating that location in the src: property and see if that works.

Activity icon

Replied to Spatie / Eloquent-sortable - Please Help To Integrate Spatie Code... HELP

You can't see any differences between the example and your model? Go line-by-line and see if you can see what you need to change.

Activity icon

Replied to Your Card Has Insufficient Funds. Why If My Balnce More Than

It's not popularized, but you can pay by PayPal here: https://laracasts.com/paypal

Activity icon

Replied to PayPal SDK V2

As a personal note, I found using the omnipay/paypal package was infinitely easier than trying to implement the entire PayPal API from scratch.

Activity icon

Replied to 500 Internal Server Error On Laravel Forge 2nd Database

Also make sure that if you're adding values to your .env file that you run php artisan config:clear and php artisan config:cache for it to pick up the new settings

Jun
24
3 months ago
Activity icon

Replied to Accessor Not Working

If you have the accessor named the same thing as the actual column, you have to use $this->attributes['walkover_only'] because of the naming conflict

Activity icon

Replied to InvalidArgumentException: Unable To Locate Factory For [App\Thread].

Because booting the entire framework defeats the purpose of unit testing. They've left it for the feature/integration test stubs as in those cases it makes sense to boot the entire framework, but when you're testing a single model, that's the definition of a single unit and so you shouldn't need to use all of Laravel for it.

Jun
23
3 months ago
Activity icon

Awarded Best Reply on Laravel 7 Testing With Codeception Or PHPUnit/Dusk

Laravel is already good to go with PHPUnit/Dusk. Dusk is even specifically built by the Laravel team. Dusk and PHPUnit should be all you need to begin testing.

Activity icon

Replied to Laravel 7 Testing With Codeception Or PHPUnit/Dusk

Laravel is already good to go with PHPUnit/Dusk. Dusk is even specifically built by the Laravel team. Dusk and PHPUnit should be all you need to begin testing.

Activity icon

Replied to Laravel Deployments

The way almost everyone I know does it is creates a CICD-ready .env-like file but calls it .env.cicd or something similar with their dev/testing keys in it and then in one step of the pipeline, they copy/rename .env.cicd to .env.

This is my .gitlab-ci.yml which includes that step:

stages:
  - preparation
  - building
  - testing
  - security
  - deployment

# Variables
variables:
  MYSQL_ROOT_PASSWORD: root
  MYSQL_USER: mysql_user
  MYSQL_PASSWORD: mysql_password
  MYSQL_DATABASE: mysql_db
  DB_HOST: mysql

cache:
  key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"

composer:
  stage: preparation
  image: edbizarro/gitlab-ci-pipeline-php:7.4
  script:
    - php -v
    - composer install --prefer-dist --no-ansi --no-interaction --no-progress --no-scripts
    - cp .env.cicd .env
    - php artisan key:generate
  artifacts:
    paths:
      - vendor/
      - .env
    expire_in: 1 days
    when: always
  cache:
    paths:
      - vendor/

yarn:
  stage: preparation
  image: edbizarro/gitlab-ci-pipeline-php:7.4
  script:
    - yarn --version
    - yarn install --pure-lockfile
  artifacts:
    paths:
      - node_modules/
    expire_in: 1 days
    when: always
  cache:
    paths:
      - node_modules/

build-assets:
  stage: building
  image: edbizarro/gitlab-ci-pipeline-php:7.4
  # Download the artifacts for these jobs
  dependencies:
    - composer
    - yarn
  script:
    - yarn --version
    - yarn run production --progress false
  artifacts:
    paths:
      - public/css/
      - public/js/
      - public/fonts/
      - public/mix-manifest.json
    expire_in: 1 days
    when: always

phpunit:
  stage: testing
  services:
    - mysql:5.7
  image: edbizarro/gitlab-ci-pipeline-php:7.4
  # Download the artifacts for these jobs
  dependencies:
    - build-assets
    - composer
  script:
    - php -v
    - sudo cp /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini /usr/local/etc/php/conf.d/docker-php-ext-xdebug.bak
    - echo "" | sudo tee /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
    - php artisan migrate
    - php artisan passport:install
    - ./vendor/phpunit/phpunit/phpunit --version
    - phpdbg -qrr ./vendor/phpunit/phpunit/phpunit -v --colors=never --stderr --coverage-clover=coverage.xml
    - sudo cp /usr/local/etc/php/conf.d/docker-php-ext-xdebug.bak /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
    - export CODECOV_TOKEN="MY CODECOV TOKEN - YOU SHOULD GET YOUR OWN"
    - bash <(curl -s https://codecov.io/bash) || echo 'Codecov failed to upload'
  artifacts:
    paths:
      - ./storage/logs # for debugging
    expire_in: 1 days
    when: on_failure

phpcpd:
  stage: testing
  image: edbizarro/gitlab-ci-pipeline-php:7.4
  script:
    - test -f phpcpd.phar || curl -L https://phar.phpunit.de/phpcpd.phar -o phpcpd.phar
    - php phpcpd.phar app/ --min-lines=50
  dependencies: []
  cache:
    paths:
      - phpcpd.phar

sensiolabs:
  stage: security
  image: edbizarro/gitlab-ci-pipeline-php:7.4
  script:
    - test -d security-checker || git clone https://github.com/sensiolabs/security-checker.git
    - cd security-checker
    - composer install
    - php security-checker security:check ../composer.lock
  dependencies: []
  cache:
    paths:
      - security-checker/
Jun
19
4 months ago
Activity icon

Replied to Git Not Ignoring .gitignore

Hey there @alexj123, if either of our responses helped you, can you please mark the one that helped as "Best Answer" to help future searchers out?

Jun
18
4 months ago
Activity icon

Awarded Best Reply on Disable Escaping During Tests

I actually just found a better solution that was checked in to the 7.x branch back in January.

Instead of using ->assertSee($model->name); I tried ->assertSee($model->name, false); and it works beautifully. The false tells it not to escape.

Activity icon

Replied to Disable Escaping During Tests

I actually just found a better solution that was checked in to the 7.x branch back in January.

Instead of using ->assertSee($model->name); I tried ->assertSee($model->name, false); and it works beautifully. The false tells it not to escape.

Activity icon

Started a new Conversation Disable Escaping During Tests

I'm trying to validate that a JSON response contains some particular data, but when using $faker->name occasionally it provides a name with an apostrophe character which ->assertSee($model->name); tries to escape like this:

Failed asserting that '[{"id":2,"last_name":"O'Conner"}]' contains "O&amp;#039;Conner".

Can someone tell me the correct way to validate this?

Activity icon

Replied to My View Is Not Getting Anything From The Controller. No Idea Why Can You See Why?

Can you dd($news); before the $news->load(); in the controller to see what it's showing? Then try again after the $news->load(); to see if it's loading the correct data?

Activity icon

Replied to Git Not Ignoring .gitignore

And if you've added it to your gitignore after it's been committed once, you'll need to do: git rm --cached /vendor and then do a new commit to force the changes.

You can check that you've done it right after by doing git check-ignore -v -- /vendor to ensure that it's now being caught by your new rule (it won't trip before you do the git rm --cached).

Jun
17
4 months ago
Activity icon

Awarded Best Reply on Are There Any Pitfalls With Same Queues On Different Servers?

Theoretically, there should be no problem running queue workers on multiple servers, but as @martinbean said, if you have high enough traffic levels to need 2 servers, you should probably not run your queue in the MySQL database (unless you want to kill performance), and rather use Redis or Amazon SQS (or your cloud provider's queue offering).

Activity icon

Replied to Purifier Does Not Remove Scripts

Can you post your rules list?

Activity icon

Replied to [L5.5]sometimes Db Connections Refused

Which database type are you trying to connect to (MySQL, SQLite, etc.)?

Activity icon

Replied to Want To Fetch API Data From Third Party Link?

I'm not sure what you're asking; why don't you want to use Guzzle? If you bring it in through composer, it will work exactly like any other function (like file_get_contents();).

Activity icon

Replied to Are There Any Pitfalls With Same Queues On Different Servers?

Theoretically, there should be no problem running queue workers on multiple servers, but as @martinbean said, if you have high enough traffic levels to need 2 servers, you should probably not run your queue in the MySQL database (unless you want to kill performance), and rather use Redis or Amazon SQS (or your cloud provider's queue offering).

Activity icon

Replied to My Referral System Is Not Working

What is the problem?

Activity icon

Replied to Prefixing API Routes With A Version Number - Best Approach

When I worked for a very large airline, your process is effectively the exact same one we used.

There's no need to complicate things.

Activity icon

Replied to Want To Fetch API Data From Third Party Link?

Can you just use Guzzle?

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'http://apiweqrher.com/repository/weather/latest/latest.csv');
$csv = $res->getBody();
Jun
16
4 months ago
Activity icon

Awarded Best Reply on PHPUnit Will Not Use :memory: Database

So it turns out that even though I had defined the phpunit.xml file to use ":memory:", at some point I had edited config/sessions.php from 'driver' => env('SESSION_DRIVER', 'database'), to 'driver' => 'database',so it was still trying to use the database for sessions.

Fixed it back to what it should have been, and now my entire test suite has gone down from around 90 minutes to ~5.

Thanks @diegoaurino for your suggestions, but it turns out you can't fix stupid.

Activity icon

Replied to PHPStorm & Laravel

To expand on what @m7vm7v said, once you install the laravel-ide-helper package, you'll want to run:

php artisan ide-helper:generate
php artisan ide-helper:meta

Which will actually generate the files PHPStorm needs to autocomplete your code.

Apr
25
5 months ago
Activity icon

Awarded Best Reply on How Do I Get The Value From An Encrypted Cookie?

I ended up adding

$this->disableCookieEncryption();

to my test which allowed the

$this->withCookie(...

stuff to work, and then added

->assertPlainCookie(...

to the test, since it appears that

->assertCookie(...

only accepted encrypted cookies which we've just disabled.

I have not had a chance to test the functionality in a "real" scenario yet, but this at least gets the test passing.

Activity icon

Replied to How Do I Get The Value From An Encrypted Cookie?

I ended up adding

$this->disableCookieEncryption();

to my test which allowed the

$this->withCookie(...

stuff to work, and then added

->assertPlainCookie(...

to the test, since it appears that

->assertCookie(...

only accepted encrypted cookies which we've just disabled.

I have not had a chance to test the functionality in a "real" scenario yet, but this at least gets the test passing.

Activity icon

Started a new Conversation How Do I Get The Value From An Encrypted Cookie?

Ok, in a test, I'm doing:

$cookie_value = md5(mt_rand(0, 9999999999));
dump($cookie_value);
        
$this->withCookie('cart_id', $cookie_value)->
    post(route('cart.store', [
...

and in the controller I'm doing:

dd($request->cookie('cart_id'));

This results in:

PHPUnit 8.5.4 by Sebastian Bergmann and contributors.

"9e61cbe1c2bbff1a88ec2ce4708e3474"
"eyJpdiI6IndpYlJ1R2lEV3g2L2FWaWh4cmlEdGc9PSIsInZhbHVlIjoiWkhvM21sTmx5MTg2UmpOc0x3NGdYTlBCME5GZTJBRmpIcFNDc0V3dVpXRXpyM0dSVUJUVk9SdkFybnl3YWtzNSIsIm1hYyI6IjZiNThiMWFhMWU0ZjhjZTViZWQ0ZjYzMDY2ZWQ0NmUzOTEwNzFmY2MyNzhjNmNhNjA5ZjE4NWRjZDJmMDAxOWMifQ=="

which means that in the test I get the expected MD5, but the controller is spitting out that base64-encoded string that decodes to

{"iv":"vXUcUqgt3SKCKmrwKlDHcg==","value":"9nuqOXX/dTBhAX6cJiLRVF3wbVl0avj6BMnPPUPL/kN7C05Y3IoDHZdfsqGnWG6t","mac":"5f04d7fd0d03251d49478c3c1dd2b2e376b34d50ea73919693af7b24bc5d90b7"}

which is what I'm assuming is the EncryptCookies middleware doing its thing.

What I don't understand is how do I access the decrypted value instead of the encrypted one?

When I tried adding

$cookie = decrypt($request->cookie('cart_id'), true);

dd($cookie);

to the controller, I'm not sure what would happen but I'm assuming the controller crashed because instead of the 'dd' ending the process, it's like it failed back to the test, which then failed.

If I do:

try {
    decrypt($request->cookie('cart_id'));
} catch (\Exception $e) {
    dd($e->getMessage());
}

I get:

"dd8966131cff0cb5531e8fa8e3605aa6"
"unserialize(): Error at offset 0 of 32 bytes"

If I do:

try {
    decrypt(base64_decode($request->cookie('cart_id')));
} catch (\Exception $e) {
    dd($e->getMessage());
}

I get:

"3b2548b3269aa9a02a5ea49b233ae0a9"
"The payload is invalid."

Can anyone tell me the very obvious step I'm missing here?