tylerssn

tylerssn

Member Since 3 Years Ago

Experience Points
13,290
Total
Experience

1,710 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
126
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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
13,290 XP
Apr
01
6 months ago
Activity icon

Replied to How To Mock HasMany() Resonse

@KFIRBA - I hope to test your suggestion later today.

You're not the first person that I've seen take a stance against mocking eloquent. I'm new to testing, so I'm happy to hear your reasoning.

Mar
30
6 months ago
Activity icon

Started a new conversation How To Mock HasMany() Resonse

I have test that attempts to mock a call to a hasMany() relationship (versions() below). The problem is that first() on the relationship always returns null.

    public function testGetDefaultVersion()
    {
        /**
         * Mock Config::get('docs') and assert that it will be called in this test at some point
         */
        $repoId = 'main';
        /**
         * @var Documentation $documentationMock
         */
        $documentationMock = factory('App\Documentation')->make(['id'=>0,'label'=>$repoId]);

        $documentationVersions = new Collection([
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'development']),
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'main']),
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'yas yas yas']),
        ]);

        DocumentationFacade::shouldReceive('where')->with('label', $repoId)->once()
            ->andReturn(new Collection([$documentationMock]));
        DocumentationFacade::shouldReceive('versions')->once()
            ->andReturn($documentationVersions);

        $actualDefaultVersion = $documentationMock::getDefaultVersion('main');
        $this->assertIsString($actualDefaultVersion);
    }

The static getDefaultVersion() method looks like this:

public static function getDefaultVersion(string $repo): string
    {
        return (string) Facades\Documentation::where('label', $repo)
            ->first()
            ->versions()
            ->first()
            ->version;
    }
Activity icon

Replied to Having Trouble Testing This Static Method

@DIEGOAURINO - Nesting $documentationMock in a collection moved me forward.

        DocumentationFacade::shouldReceive('where')->with('label', $repoId)->once()
            ->andReturn(new Collection([$documentationMock]));

I just need to figure out how to mock ->versions() which is an alias for ->hasMany('App/DocumentationVersions'). I'll open a new thread if needed.

Activity icon

Replied to Having Trouble Testing This Static Method

@DIEGOAURINO - Thanks for taking a second to respond. That's the obstacle that I am trying to overcome. I'm trying to mock the database data since the DB table could potentially be empty at the time of the test.

Activity icon

Started a new conversation Having Trouble Testing This Static Method

I have two models: Documentation and DocumentationVersion. I am trying to test the Documentation class static method shown below.

    public static function getDefaultVersion(string $repo): string
    {
        return (string) Facades\Documentation::where('label', $repo)
            ->first()
            ->versions()
            ->first()
            ->version;
    }

The test below returns Error: Call to a member function versions() on null.

    public function testGetDefaultVersion()
    {
        /**
         * Mock Config::get('docs') and assert that it will be called in this test at some point
         */
        $repoId = 'main';
        /**
         * @var Documentation $documentationMock
         */
        $documentationMock = factory('App\Documentation')->make(['id'=>0,'label'=>$repoId]);

        $documentationVersions = new Collection([
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'development']),
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'main']),
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'yas yas yas']),
        ]);

        DocumentationFacade::shouldReceive('where')->once()
            ->andReturn($documentationMock);
        DocumentationFacade::shouldReceive('first')
            ->andReturn($documentationMock);
        DocumentationFacade::shouldReceive('versions')
            ->andReturn($documentationVersions);

        $actualDefaultVersion = $documentationMock::getDefaultVersion('main');
        $this->assertIsString($actualDefaultVersion);
    }

Any guidance would be greatly appreciated.

Feb
01
8 months ago
Activity icon

Started a new conversation Should I Care About Other Third-party Unit Tests Passing?

I'm trying to wrap my head around what I should and should not concern myself with when it comes to unit tests.

One of the frameworks that I use is Magento which comes with a unit testing suite for their packages, and oddly, packages in vendor/*/module-*. Out of the box, of course, all of those tests pass and I would like them to continue to pass.

It seems to me, though, that I should only care about my code and it's impact on the framework and that I shouldn't concern myself with third-party tests. Even if I do concern myself with with their tests, a unit test shouldn't break even if new packages extend or replace their functionality, right? ...because all of those tests should be isolated and mocked anyway?

Jan
23
2 years ago
Activity icon

Replied to PDO - InvalidArgumentException In JsonResponse.php Line 58: Malformed UTF-8 Characters, Possibly Incorrectly Encoded

Yes! And I can finally move forward with PHP 7.

Summary, Cause, and General Fix

See my Laracast post and answer here for how I setup Laravel DB and Eloquent classes to automatically resolve this.

From my StackOverflow Answer

As explained in this pull request, the cause of this issue in PHP 7 is that you have to instruct PDO to convert the GUIDs from binary to a string.

This should do it for anyone struggling with this.

    /** @var \PDO $pdo */
    $pdo->setAttribute(\PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER, true);
Jan
05
2 years ago
Activity icon

Replied to Model Not Acknowledging New PDO Settings

This actually worked fine. The issue was that my model had a one to many relationship with another table that used GUIDs that I had to apply this same logic to.

Solution - Auto update any models connecting to MSSQL by overriding model boot method

First, I created a scope to update the PDO connection:

<?php 

namespace App\Api\V2\Model\Rule;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class StringifyGuidRule implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder $builder
     * @param  \Illuminate\Database\Eloquent\Model $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $hasPhp7GuidHelper = defined('\PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER');
        if ($hasPhp7GuidHelper):
            $model->getConnection()->getPdo()->setAttribute(\PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER, true);
        endif;
    }
}

Lastly, add the following to your model class:

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    //Any time this model is used, it will implement the StringifyGuidRule
    static::addGlobalScope(new StringifyGuidRule());
}
Jan
04
2 years ago
Activity icon

Started a new conversation Model Not Acknowledging New PDO Settings

It turns out that in PHP 7.0 and up we have to manually configure PDO to not return the binary version of GUID. To implement the new PDO feature, I added setAttribue to my connection as shown:

    $connection = DB::connection('remoteRecipes');
    $php7GUIDHelper = defined('\PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER');
    if ($php7GUIDHelper):
        $connection->getPdo()->setAttribute(\PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER, true);
    endif;
    
    return $connection->table('Recipe')...

This resolved my GUID issue. However, the same does not work for models. I tried the following:

    $attributeModel = AttributeOptionsMap::where('apiId', $attribute);
    $php7GUIDHelper = defined('\PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER');
    if ($php7GUIDHelper):
        $attributeModel->getConnection()->getPdo()->setAttribute(\PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER, true);
    endif;
    $attributeModel = $attributeModel->first();

Should I attempt to manipulate the PDO parameter during the construction of the class? If so, how?

Nov
16
2 years ago
Activity icon

Replied to PDO - InvalidArgumentException In JsonResponse.php Line 58: Malformed UTF-8 Characters, Possibly Incorrectly Encoded

Strangely, this only appears to impact GUIDs. This is occurring during my attempt to upgrade my site to PHP 7 and my research seems to be pointing to lack of UTF-8 support in drivers as the culprit.

Oct
20
2 years ago
Activity icon

Started a new conversation Why Does Laravel Symlink Storage?

Out of pure curiosity and understanding the difference - why is storage symlinked rather than being placed in the public directory?

Sep
07
3 years ago
Activity icon

Started a new conversation PDO - InvalidArgumentException In JsonResponse.php Line 58: Malformed UTF-8 Characters, Possibly Incorrectly Encoded

In my production and local environment I have the MSSQL DB config shown below.

    'recipeDB' => [
        'driver' => 'sqlsrv',
        'host' => env('DB_HOST', 'host'),
        'database' => env('DB_DATABASE', 'database'),
        'username' => env('DB_USERNAME', 'username'),
        'password' => env('DB_PASSWORD', 'password'),
        'charset' => 'UTF-8',
        /** Updating collation does not appear to do anything */
        'collation' => 'SQL_Latin1_General_CP1_CI_AS',
        'prefix' => '',
    ],

Selecting from this database and converting to JSON works perfectly in production (PHP5), however, in my test environment (PHP7) I get the following error:

 Malformed UTF-8 characters, possibly incorrectly encoded

If I changed my PDO charset from UTF-8, I can no longer connect.

EDIT

The Collation for the database is SQL_Latin1_General_CP1_CI_AS - I'm not sure how that translates to charset.

More Details

  • PHP Version: PHP 7.0.8-3ubuntu2 (cli) ( NTS )

  • Framework: Laravel 5.2

  • PDO & Driver Config: Shown Above

  • Data Returned from dd(DB::connection('recipeDB')->table('Recipe')->first())

      {#322
      +"recGUID": b"›E•_K¿\x1CHŸü\x00\x00ât\x03Ž"
      +"location": "France"
      +"locationid": 3
      +"description": "Tangerina"
      +"publishedname": "Tangerina"
      +"instructions": ""
      +"alcohol": 1
      +"web": 0
      +"PublicationExists": 0
      +"GlobalMobileApp": 0
      +"credat": "2009-12-16 00:00:00"
      +"updat": "2011-05-19 12:14:21"
      +"servingsize": null
      +"isCoffee": 1
      +"isFood": 1
      +"isHome": 1
      +"isBar": 1
      +"colorid": b"+Üp{b%ÃB┤ä┘Ãú÷┌ü"
      +"equipmentid": b"–lOW¾…yDˆÜ¦ù§\x03E!"
      +"bevtypeid": b"ã®få†$ÃD¹êò\[email protected]×K•"
      +"serveid": b"═HØ»\x19Ô8Aûv<╝¡zÎ\v"
      +"glassid": b"O¾\x16C<i‡G±!³#GÇ\x15É"
      +"methodid": null
      +"servingsizeuomid": null
      +"LastEditDate": "2013-10-30 20:05:06"
      +"CreationDate": "2010-06-10 17:08:46"
      +"proprietary": 1
      +"Rating": -1
      +"LevelOfDifficulty": 4
      +"Enable": 1
      }
    
  • Error:

      InvalidArgumentException in /home/user/PhpStorm/Projects/recipeApi/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php line 58:
      Malformed UTF-8 characters, possibly incorrectly encoded
    
  • Error Trace:

       1. in JsonResponse.php line 58
       2. at JsonResponse->setData(array('data' => array(array('recipeId' => '�N��D��E�MH�4>�', 'alt_id'=>null...
    
Apr
28
3 years ago
Activity icon

Started a new conversation Can My DB Query Live Within My Eloquent Model?

I have a Recipe Eloquent model. With so many relationships it was too inefficient (read "slow") to use for a RESTful API response. I get much better performance using the DB query shown below, and then the cache on top of that takes what took up to 30 seconds before and delivers it in less than a second. I understand that maybe a better method would be to have a single flat table for API request such as the one shown below, but that isn't immediately possible.

So...

  1. I'd like to have all of my recipe methods continue to live in one place, whether it be an Eloquent model or elsewhere. Should the query below be a method within my model?
  2. Can my DB query be done in Eloquent without sacrificing performance?
  3. If the query below cannot live within my model, is there any literature on where a DB query should live so that it is easier to manage the object and keep it scalable?

Details:

$recipes = Cache::remember("query-recipe-all-{$this->getLocation()}-{$this->getItemsPerPage()}-{$request->input("start")}-{$request->input("end")}", $cacheExpireAfterMinute, function () {
    return DB::connection('remoteRecipes')->table('Recipe')
       ->join('HowServed', 'Recipe.serveid', '=', 'HowServed.serveid')
       ->join('Colors as Color', 'Recipe.colorid', '=', 'Color.colorid')
       ->join('Glass as GlassType', 'Recipe.glassid', '=', 'GlassType.glassid')
       ->join('BeverageType', 'Recipe.bevtypeid', '=', 'BeverageType.bevtypeid')
       ->join('UOM as UnitOfMeasure', 'Recipe.servingsizeuomid', '=', 'UnitOfMeasure.uomid')
       ->join('Equipment', 'Recipe.equipmentid', '=', 'Equipment.equipmentid', 'full outer')
       ->join('Methods as Method', 'Recipe.methodid', '=', 'Method.methodid')
       ->join('RecipeImages as Images', 'Recipe.recGUID', '=', 'Images.RecipeID')
       ->select(
          'Recipe.recGUID as masterRecipeId',
          'Recipe.MoninDotCom_SKU as alt_id',
          'Recipe.credat as date_created',
          'Recipe.updat as date_updated',
          'Recipe.locationid as locationId',
          'Recipe.location as locationTextId',
          'Recipe.publishedname as titlePreferred',
          'Recipe.description as title',
          'HowServed.serveid as servedHowId',
          'HowServed.served as servedHowLabel',
          'HowServed.location as servedHowLocation',
          'Color.colorid as colorId',
          'Color.color as colorLabel',
          'Color.location as colorLocation',
          'GlassType.glassid as glassTypeId',
          'GlassType.glass as glassTypeLabel',
          'GlassType.location as glassTypeLocation',
          'Recipe.LevelOfDifficulty as levelOfDifficultyId',
          'Recipe.alcohol as hasAlcohol',
          'BeverageType.bevtypeid as beverageTypeId',
          'BeverageType.bevtype as beverageTypeLabel',
          'BeverageType.location as beverageTypeLocation',
          'Recipe.servingsize as servingSize',
          'UnitOfMeasure.uomid as uniteOfMeasureId',
          'UnitOfMeasure.uom as uniteOfMeasureLabel',
          'UnitOfMeasure.location as uniteOfMeasureLocation',
          'Equipment.equipmentid as equipmentId',
          'Equipment.equipment as equipmentLabel',
          'Equipment.location as equipmentLocation',
          'Recipe.Rating as recipeTagRatingInternal',
          'Recipe.isCoffee as recipeTagIsCoffee',
          'Recipe.isFood as recipeTagIsCulinary',
          'Recipe.isHome as recipeTagIsForHome',
          'Recipe.isBar as recipeTagIsForBar',
          'Method.methodid as methodId',
          'Method.methodName as methodLabel',
          'Method.location as methodLocation',
          'Recipe.Instructions as instructions',
          'Recipe.recGUID as IngredientsLookupId',
          'Recipe.recGUID as GetProductsUsedInIngredients',
          'Recipe.recGUID as Garnish.LookupId',
          'Recipe.recGUID as Seasons.LookupId',
          'Images.*'
       )
       ->where('Recipe.location', '=', $this->getLocation())
       ->where('Recipe.web', '=', 1)
       ->where('Images.apptype', '=', "monin.com US")
       ->whereBetween('Recipe.updat', [$this->getListFromDate(), $this->getListToDate()])
       ->orderBy('Recipe.updat', 'DESC')
       ->paginate($this->getItemsPerPage());
  });
Apr
27
3 years ago
Activity icon

Started a new conversation DB Join - Trouble Including Null Values

I am joining multiple tables using the DB class. This is pulling in accurately except when UOM.uomid is null. When uomid is null I still want there to be a row containing the other data - I do not want the row to be excluded.

Any guidance would be greatly appreciated.

    $ingredientLines = DB::connection('remoteRecipes')->table('RecipeLines')
        ->join('Brand', 'Brand.brandid', '=', 'RecipeLines.brandid')
        ->join('fractions', 'fractions.PK_qtys', '=', 'RecipeLines.fractID')
        ->join('UOM', 'UOM.uomid', '=', 'RecipeLines.uomid')
        ->join('Ingredient', 'Ingredient.ingredientid', '=', 'RecipeLines.ingredientid')
        ->join('Product', 'Product.productid', '=', 'RecipeLines.productid')
        ->select(
            'RecipeLines.*',
            'fractions.rep as fractionRep',
            'UOM.uom as uomLabel',
            'Brand.brandid as brandId',
            'Brand.brand as brandLabel',
            'Product.productid as productId',
            'Product.product as productLabel',
            'Ingredient.ingredientid as ingredientId',
            'Ingredient.ingredient as ingredientLabel'
        )
        ->where('RecipeLines.recipeid', '=', $recipeId)
        ->orderBy('no_servings','ASC')->orderBy('sortorder','ASC')
        ->get();
    if (!empty($ingredientLines)):
        return $ingredientLines;
    endif;
Mar
28
3 years ago
Activity icon

Replied to Assistance Needed In Optimizing Model Implementing A Few Relationships

Unfortunately, I have no say over the structure of the database. I'm tasked with outputting this data in the form of a JSON response. I'm working with the DB admin to ensure that all of the indexes are properly established.

Activity icon

Replied to Assistance Needed In Optimizing Model Implementing A Few Relationships

They're all models. Can you provide insight into a more efficient means of outputting the same data with fewer calls to the database?

Activity icon

Started a new conversation Assistance Needed In Optimizing Model Implementing A Few Relationships

EDIT: I thought I would be able to resolve this by implementing the following but it is still quite slow and the selects do not appear to be merged into joins.

Recipe::with(['color', 'glass', 'garnishes', 'recipeLines.fraction','recipeLines.unitOfMeasure','recipeLines.brand','recipeLines.product','recipeLines.ingredient', 'method', 'howServed', 'equipment', 'uom', 'products'])

tldr;

I have the following in my index controller:

    $recipes = Recipe::with(['color', 'glass', 'garnishes', 'recipeLines.fraction','recipeLines.unitOfMeasure','recipeLines.brand','recipeLines.product','recipeLines.ingredient', 'method', 'howServed', 'equipment', 'uom', 'products'])->where('location', $this->getLocation())
        ->whereBetween('updat', array($this->getListFromDate(), $this->getListToDate()))
        ->paginate($this->getItemsPerPage());

I thought that by using with() that Laravel would change my model relationships from individual selects to joins when Recipe::all() is called but when I look at DB::connection('remoteRecipes')->getQueryLog() I see 50 select queries instead of one.

Mar
24
3 years ago
Activity icon

Started a new conversation Struggling With HasManyThrough

I am attempting pull a list of items using a middle table as a lookup table. A single recipe can have multiple garnishes. My goal is to have my recipe model return a list of garnishes through $recipe->garnishes.

The DB admin setup the tables in the following format (showing relevant columns only):

  1. Recipe - Home to all of our recipes
    • recGUID (Recipe ID column)
  2. RecipeGarnishMembership - Used as a lookup table for garnishes within a recipe, associated by recipe ID)
    • recipeid (Recipe ID column)
    • garnishid (Garnish ID column)
  3. Garnishes - Home to all of our garnishes
    • garnishid (Garnish ID column)

Currently I am trying:

/**
 * The garnishes that belong to the recipe.
 */
public function garnishes()
{
    $recipeGarnishes = $this->hasManyThrough('App\Garnishes', 'App\RecipeGarnishMembership','recipeid','garnishid');
    dd($recipeGarnishes); 
}
Mar
11
3 years ago
Activity icon

Started a new conversation Struggling With WhereBetween On MSSQL Database.

I am trying to use the following query to pull a list of recipes between the dates specified;

    $start=Carbon::createFromDate(2016,3,1);
    $end = Carbon::now();
    $recipes = Recipe::where('location', $location)
        ->whereBetween('updat', array($start, $end))
        ->paginate($this->getItemsPerPage());    

These start/end dates return data but the following start does not when there are results within these dates.

$start=Carbon::createFromDate(2016,3,7);
Mar
09
3 years ago
Activity icon

Replied to What Is The Best Way To Implement A Custom "is_active" Field Using Multiple Columns?

Thanks folks. Between OP time and now I stumbled across query scopes and implemented something similar to what's shown above.

@tykus_ikus, thanks for the bonus $recipe->is_active guidance.

Activity icon

Started a new conversation What Is The Best Way To Implement A Custom "is_active" Field Using Multiple Columns?

I'm building an API that will be feeding recipes to a website. I want queries (Recipe::all(), Recipe::where(), etc..) to default to the following column filters:

| COLUMN_NAME | DEFAULT_FILTER

Enabled | 1
Web | 1