bcharron

Web Developer at Sephone Interactive Media

Experience

1,410

0 Best Reply Awards

  • Member Since 1 Year Ago
  • 9 Lessons Completed
  • 0 Favorites

22nd August, 2018

bcharron left a reply on Create Method Saving Null Values • 2 months ago

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 • 2 months ago

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?

21st August, 2018

bcharron started a new conversation Inserting Many Records With An Association • 2 months ago

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?

16th August, 2018

bcharron left a reply on Create Method Saving Null Values • 2 months ago

@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 • 2 months ago

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 • 2 months ago

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

14th August, 2018

bcharron started a new conversation Create Method Saving Null Values • 2 months ago

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?

24th July, 2018

bcharron left a reply on Updating Multiple Many To Many Relationships • 2 months ago

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.

20th July, 2018

bcharron started a new conversation Updating Multiple Many To Many Relationships • 3 months ago

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
        ]
    );
}

13th July, 2018

bcharron left a reply on Retrieving BelongsTo Relationship • 3 months ago

@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 • 3 months ago

@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 • 3 months ago

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

bcharron started a new conversation Retrieving BelongsTo Relationship • 3 months ago

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?

15th June, 2018

bcharron left a reply on MySQL With SSL Returns Bad Gateway • 4 months ago

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

14th June, 2018

bcharron started a new conversation MySQL With SSL Returns Bad Gateway • 4 months ago

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?

15th December, 2017

bcharron left a reply on FirstOrCreate/New With MySQL Operators • 10 months ago

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 • 10 months ago

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?

28th November, 2017

bcharron started a new conversation Filesystem S3 Driver - Working With Object Versions • 10 months ago

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.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.