bcharron

bcharron

Web Developer at Sephone Interactive Media

Bangor, ME

Member Since 1 Year Ago

Experience Points 1,410
Experience
Level
Lessons Completed 9
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

22 Aug
3 months ago

bcharron left a reply on Create Method Saving Null Values

Thanks for the input everyone. I have had to step away from this part of the project temporarily, but it sounds like @Cronix approach would be better for me. I will try this when I can come back to it, and will mark that as the accepted answer after testing.

bcharron left a reply on Inserting Many Records With An Association

Thanks for the input @bobbybouwmann. Would it be better to do the create statement with the full $assignments array to insert all of them in one call, and then loop over the assignments to save the addresses?

21 Aug
3 months ago

bcharron started a new conversation Inserting Many Records With An Association

I am building a CSV importer. I need to save the data into a couple of tables, and associate them together, but I'd like to do this in as few calls as possible.

I have been able to get the primary table data and save it like so:

foreach ( $records as $offset => $record ) { 
    $is_record_empty = $this->_checkForEmptyRecord( $record );
    $is_record_header = $this->_checkForHeaderContent( $record );
    
    // Check if this $record entry is header row, or empty
    // and continue past it because we don't want to process it.
    if( $is_record_empty || $is_record_header ) {
        continue;
    }

    $time_slot = $this->_determineTimeSlot( $record );
    $time_slot_id = $this->_determineTimeSlotID( $time_slot );
    $address = $this->_formatAddress( $record );
    
    $user_id = ( array_key_exists( $record['Technician'], $techs ) ) ? $techs[$record['Technician']] : null;
    $job_count[$user_id] = array_key_exists($user_id, $job_count) ? $job_count[$user_id] + 1 : 0;
    
    $assignments[] = [
        'company' => 'twc',
        'identifier' => $record['Job ID'],
        'user_id' => $user_id,
        'date' => $this->date,
        'time_slot_id' => $time_slot_id,
        'points' => $record['Est Job Duration'] / 5,
        'type' => $record['Job Type'],
        'display_order' => $job_count[$user_id],
        'notified' => $notified_count ? 1 : 0,
        'created_at' => date( 'Y-m-d G:i:s' ),
        'updated_at' => date( 'Y-m-d G:i:s' ),
    ];
}

return $this->assignment->insert($assignments);

I want to associate $address with the assignment, but from what I can find I can't do this with a bulk insert. Is this the case? Would the best option be to save each assignment individually, and create the association with that save?

16 Aug
4 months ago

bcharron left a reply on Create Method Saving Null Values

@crnkovic Yes, it is in the model. Should I use the boot method instead, or is there another recommendation that you'd make?

bcharron left a reply on Create Method Saving Null Values

After some troubleshooting in the model, I have found that the following code seems to be affecting the update method:

public $location;

public function __construct( $location = null ) {
        $this->location = $location;
}

I am using this to define a property that is used elsewhere in the model, but not in the saving or creating of the model. Is there any reason why this would cause all of the values to be nulled out when trying to update the model?

bcharron left a reply on Create Method Saving Null Values

@jlrdw I did, and like I show in my code above, I have the $fillable property set.

14 Aug
4 months ago

bcharron started a new conversation Create Method Saving Null Values

I have a save method in a repository in an application that I am working on. The method looks like this:

public function save($data)
    {

        Model::create([
            'title' => $data['title'],
            'min_length' => $data['min_length'],
            'max_length' => $data['max_length'],
            'prefix' => $data['prefix'],
            'one_way' => $data['one_way']
        ]);

    }

When I call this method, it returns the saved model, but all of the values in it are empty. I have confirmed that the values are present in $data by dd'ing them. I have the $fillable property set on the model, but still I am getting null values:

protected $fillable = [

        'title',
        'min_length',
        'max_length',
        'prefix',
        'one_way',

    ];

I have changed this to use the save() method instead of create() and it works. Can anyone explain why the create method does not save the values?

24 Jul
4 months ago

bcharron left a reply on Updating Multiple Many To Many Relationships

Thanks for the response @Jawelo. From what I read, sync() is used to construct new many to many relations, not update existing ones. It also requires a list of IDs to sync the relationship with, which I don't have without doing some sort of foreach over the returned collection. I will see if I can get the list of IDs out of that and see if sync() will work for me.

20 Jul
4 months ago

bcharron started a new conversation Updating Multiple Many To Many Relationships

I am wondering if there is a best practice when it comes to updating the pivot table for a many to many relationship. I currently have the following code which updates each pivot table record individually, but wonder if there is a better way to do this?

foreach( $job->codes as $code ) {
    $job->codes()->updateExistingPivot(
        $code->id,
        [
            'approved' => 1
        ]
    );
}
13 Jul
5 months ago

bcharron left a reply on Retrieving BelongsTo Relationship

@staudenmeir Thank you, that was indeed the issue. Renaming the category column to category_legacy and I am now able to get my association using $assignment->category.

bcharron left a reply on Retrieving BelongsTo Relationship

@staudenmeir Yes, here is the code for how I am using it:

$assignment = $this->assignment
            ->with( ['category'] )
            ->findOrFail( $id )
            ;
$category = $assignment->category()->get();

If I use $assignment->category as suggested previously, I get null, if I use $assignment->category() I get the query builder instance, which is what lead me to $assignment->category()->get(). I would agree with @Cinek that just $assignment->category should work, but it doesn't.

bcharron left a reply on Retrieving BelongsTo Relationship

@Cinek When I do that, I get a null for the return value.

bcharron started a new conversation Retrieving BelongsTo Relationship

I am looking for some clarification on how to retrieve data from a belongsTo relationship. I have 2 models, Assignment and Category. An Assignment belongs to a Category and a Category hasMany Assignment. In my Assignment repository I am looking up assignments and their associated categories like so:

$assignment = $this->assignment
            ->with( ['category'] )
            ->findOrFail( $id )
            ;

This gets me the expected assignment object, and I see the category relationship object:

Assignment {#1724
  #softCascade: array:1 [
    0 => "workOrder"
  ]
  #fillable: array:130 [
    0 => "user_id"
    1 => "time_id"
    2 => "work_order"
    3 => "tag"
    4 => "company"
    5 => "identifier"
    6 => "date"
    7 => "time"
    8 => "time_slot_id"
    9 => "category"
    10 => "category_id"
    ...
  ]
  #hidden: []
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:134 [
    "id" => 430986
    "user_id" => 10006096
    "time_id" => null
    "work_order" => null
    "tag" => null
    "company" => null
    "identifier" => null
    "date" => "2017-12-21"
    "time" => "ALLDAY"
    "time_slot_id" => 50
    "category" => null
    "category_id" => 32
    ...
  ]
  #original: array:134 [
    "id" => 430986
    "user_id" => 10006096
    "time_id" => null
    "work_order" => null
    "tag" => null
    "company" => null
    "identifier" => null
    "date" => "2017-12-21"
    "time" => "ALLDAY"
    "time_slot_id" => 50
    "category" => null
    "category_id" => 32
    ...
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:1 [
    "category" => Category {#1839
      #dates: array:1 [
        0 => "deleted_at"
      ]
      #primarykey: "id"
      #fillable: array:3 [
        0 => "name"
        1 => "time_off"
        2 => "points"
      ]
      #hidden: array:3 [
        0 => "deleted_at"
        1 => "created_at"
        2 => "updated_at"
      ]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [
        "id" => 32
        "name" => "Category Name"
        "time_off" => 0
        "points" => 0
        "deleted_at" => null
        "created_at" => "2017-12-20 17:52:40"
        "updated_at" => "2017-12-20 17:52:40"
      ]
      #original: array:7 [
        "id" => 32
        "name" => "Category Name"
        "time_off" => 0
        "points" => 0
        "deleted_at" => null
        "created_at" => "2017-12-20 17:52:40"
        "updated_at" => "2017-12-20 17:52:40"
      ]
      #changes: []
      #casts: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [
        0 => "*"
      ]
      #forceDeleting: false
    }
  ]
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [
    0 => "*"
  ]
  #forceDeleting: false
}

When I try to access the category with $assignment->category() it returns what looks like a query builder object for the belongs to relationship. In order to actually return the data I need to run $assignment->category()->get(). Is there a reason that the data is not available directly, instead of having to actually get() it?

15 Jun
6 months ago

bcharron left a reply on MySQL With SSL Returns Bad Gateway

@jdc1898 I have not tried that, but this link seems to be specific to AWS RDS, which we are not using.

14 Jun
6 months ago

bcharron started a new conversation MySQL With SSL Returns Bad Gateway

I am trying to connect to a SSL enabled database with a Laravel application, but when I do so, I get a bad gateway error. Per a few different resources, I found the following configuration for the MySQL driver to add support for SSL connections, but with this driver configuration, I get the Bad Gateway error.

Driver

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'sslmode' => env('DB_SSLMODE', 'prefer'),
            'options'   => [
                PDO::MYSQL_ATTR_SSL_CA    => '/path/to/file/ca.pem',
                PDO::MYSQL_ATTR_SSL_CERT    => ''/path/to/file/client-cert.pem',
                PDO::MYSQL_ATTR_SSL_KEY    => ''/path/to/file/cleint-key.pem'
            ],
            'strict' => true,
            'engine' => null,
        ],

I am using Laravel Valet as the development environment for this. I get the following error in the Valet NGINX error log: 2018/06/14 07:51:50 [error] 6495#0: *15 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: ccc.dev, request: "POST /oauth/token HTTP/1.1"

Does anyone know how to resolve this issue with a SSL enabled DB connection in a Laravel application or on Valet?

15 Dec
1 year ago

bcharron left a reply on FirstOrCreate/New With MySQL Operators

Thank you @Dry7 & @tykus, this is what I anticipated, I just wanted to check and make sure I was not overlooking something that would accomplish what I wanted to do.

@tykus The code you provided works. Only adjustment is that the if statement check is missing a $ before dma.

bcharron started a new conversation FirstOrCreate/New With MySQL Operators

I am trying to use the firstOrCreate or firstOrNew Eloquent methods to find a record in the database by a column in a given table. I'd like to use the like MySQL operator to search for records that do not 100% match the current entry. From what I can tell, these methods only allow for the column and the value with no special operators. Is there a way to use these methods how I have described?

Here is an example of what I would like to do (does not work currently)

$dma = Dma::firstOrCreate(
    ['name', 'like', "%$market%"]
);

The above code produces the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from column where (0 = name and 1 = like and 2 = %Market%) limit 1)

I understand that this error occurs because the array is not formed properly for the firstOrCreate method, but is there a way to make this work or an alternative that will accomplish what I am looking to do?

28 Nov
1 year ago

bcharron started a new conversation Filesystem S3 Driver - Working With Object Versions

I using AWS S3 to store files that are uploaded to my application. I have 1 file that will be uploaded on a weekly basis. This file has the same name every week. S3 has an option to store versions for a specific object, thus the file will not be overwritten when uploaded each week. I am wondering if there is a way to interact with a specific version of the S3 object? I would like to get the version ID back from the Storege::put request, so that I might be able to retrieve a specific object version. When I run Storage::get($filename), I get the latest version of the file, but nothing more than the file contents. I have also tried Storage::getMetadata, but the version is not included with that information.