jbloomstrom

jbloomstrom

Member Since 4 Years Ago

Palmer

Programmer Analyst at Matanuska-Susitna Borough

Experience Points 122,845
Experience Level 25

2,155 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 1083
Lessons
Completed
Best Reply Awards 31
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.

16 Sep
3 days ago

jbloomstrom commented on Explain PHP Generators

For large numbers, I usually write them in E-notation to avoid mistakes and make it easier to visually parse later. Works in PHP, JS, and many other languages.

1e3 === 1000;
1e6 === 1000000;
6.022e23 === 602200000000000000000000;
13 May
4 months ago

jbloomstrom left a reply on Validation: Sometimes|Required

@fundi sometimes|required will invalidate empty or null strings if the field is present in the request. It's not particularly clear in the docs, but that's the intended behavior.

You'll want to remove those fields from the request if they are empty. If you're using AJAX to submit the form, just omit them from the payload data. If you're using traditional forms, you can separate the password reset inputs to their own form or disable them before submitting the form if they are empty.

window.disableFieldIfEmpty = function(field_id) {
  let field = document.getElementById(field_id);
  
  if ( ! field )
    return;
  
  if( ! field.value.trim().length ) {
    field.disabled = true; 
  }
}

Here is an example in Codepen. https://codepen.io/anon/pen/eadXox

jbloomstrom left a reply on Validation: Sometimes|Required

It sounds like the current_password parameter is being passed in the request, perhaps as an empty string. Put dd($request->all()) at the top of your update method. That will tell you all the parameters that are coming through in the request.

public function update(Request $request)
{
    dd($request->all());
    // the rest of the method body...
}
08 May
4 months ago

jbloomstrom left a reply on Linting Eloquent Delete Throws A Non-annotated/unhandled Exception

Refer to the api docs. The delete method throws \Exception. Wrap your delete logic in a try catch block or add @throws \Exception to your DocBlock.

01 May
4 months ago

jbloomstrom left a reply on If Remote Img Src Exists?

You can use curl to check if the image exists.

function url_exists($url){
    $ch = curl_init($url);    
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

   return ($code == 200);
}

$url = url_exists("http://logo.clearbit.com/ryanm.com") ? 
    "http://logo.clearbit.com/ryanm.com" : 
    "<alternate_url>";
24 Apr
4 months ago

jbloomstrom left a reply on Advice On How To Handle Authentication And Access For An Expired Subscription?

A user's subscription status isn't likely to change often, so it seems a good candidate for long-term caching. Update the cached value when the subscription status changes. That will save a db query with each request.

class User {


    function subscribed() 
    {
        $cacheKey = "users.{$this->id}.subscribed";

        return \Cache::remember($cacheKey, 24 * 60 * 60, function() {
            return $this->hasValidSubscription() || $this->isOnTrial();
        }
    }

    function hasValidSubscription()
    {
        // TODO: Implement Logic
    }

    function isOnTrial()
    {
        // TODO: Implement Logic
    }


}

jbloomstrom left a reply on How To Have A Image Preview In The Light Box For Before Uploading In The Form

You are using data-rel in your html, but your jQuery selector is using data-img.

Should this

$imageid = $(this).attr('data-img');

be this?

$imageid = $(this).attr('data-rel');
18 Apr
5 months ago

jbloomstrom left a reply on Let User Upload Any Photo Size - Resize Later

Check out the Intervention library. I use it for optimizing uploaded images by broadcasting an event when an image is uploaded. Then I have a listener kick off a job that runs my optimization routine.

The whole process is covered in depth at Test Driven Laravel

08 Apr
5 months ago

jbloomstrom left a reply on Axios Make Double Request To My Server In My Network Tab

@JEFRYDCO - Sorry for the delay, I just saw this. Using .prevent tells Vue to ignore the default behavior of the event (submit, in this case). It's equivalent to using event.preventDefault. You can read more about it here: https://vuejs.org/v2/guide/events.html#Event-Modifiers

27 Mar
1 year ago

jbloomstrom left a reply on Vue, Laravel, Echo Help

Do you have the Vue Devtools extension for Chrome? It's a huge help for these situations.

Can you inspect the data-project prop in the devtools extension. Does it have an id value? Is the project being passed to the TaskList component properly?

Are you remembering to pass the project object to the component?

Make sure you are passing it like this:

<task-list :data-project="project"></task-list>

or

<task-list v-bind:data-project="project"></task-list>

not

<task-list data-project="project"></task-list>

The last example will assign the literal string "project" to the prop value.

06 Feb
1 year ago
05 Feb
1 year ago

jbloomstrom left a reply on Need A Look At A Laravel 5.5 Feature Test

If the slug column is not missing from your migration, check your $fillable or $guarded attribute on your Product model class.


class Product {

    // you need this
    protected $guarded = [];

    // or this
    protected $fillable = [
        'title',
        'slug', // this could be missing if you are using fillable
        'description'
    ];
}
18 Jan
1 year ago

jbloomstrom left a reply on Sort A Collection By A Relationship Value

Maybe you can manually sort the comments after you retrieve them from the database?

return $list->limit($limit)
    ->get()
    ->sortByDesc( function ($order,$key) {
        return optional($order->orderContactNotes)->max('created_at');
    })
    ->transform( function ($order) {
        $order->orderContactNotes = optional($order->orderContactNotes)
            ->sortBy('created_at')
            ->values();
        return $order;
    })
    ->values();

jbloomstrom left a reply on Sort A Collection By A Relationship Value

A couple things come to mind. First, I'm a bit unclear on what you're trying to accomplish. Can you post any errors or unexpected behavior that you are seeing?

I see that you are using limit in your query without specifying the order. That may give you unexpected behavior as the rows are not guaranteed to be in any particular order when they are returned from the database. In other words, you could perform the same query 100 times and get inconsistent results. See here for more about that.

jbloomstrom left a reply on Repositories

@omarsow94 Are you still getting the error? Can you post the rest of the stack trace from the error message and your ConversationRespository file?

17 Jan
1 year ago

jbloomstrom left a reply on Repositories

The error could be coming from a different file. Can you post the snippet from your laravel log that contains the full error message?

jbloomstrom left a reply on Repositories

Can you post the whole controller file?

jbloomstrom left a reply on Should A Controller Be Restricted To Creating/modifying Objects Specifically For That Model?

FWIW, when I am dealing with a resource that is a child of another resource (in your case database is a child of account) I like to be explicit with the scope of my controllers. For your example, I would have an AccountController for dealing with accounts, an AccountDatabaseController for dealing with databases that belong to a specific account, and maybe even a DatabaseController for dealing with all databases regardless of account (maybe for admin routes, etc.).

When you create your controller, you can specify a parent model to generate a nested (i.e. parent-child) resource controller. Like this:

php artisan make:controller AccountDatabaseController --parent="App\Account" --model="App\Database"

For your routes file, you can use "dot" notation like this to make nested routes:

Route::resource("accounts.databases", "AccountDatabaseController");

Hope that helps.

15 Jan
1 year ago

jbloomstrom left a reply on Problem Binding Vue Variable

@gabykant Did you check out the codepen? It seems to be working there. You may be getting a JS error, did you look at the browser console?

jbloomstrom left a reply on What Would You Choose? Firebase Or Pusher?

I like Pusher for its ease of use, but if you think you'll have more than 100 concurrent users you'll have to upgrade to one of their paid plans. Not sure if that influences your decision.

If you haven't ruled out socket.io as a possibility, this Laravel Echo Server is a great option - https://github.com/tlaverdure/laravel-echo-server.

jbloomstrom left a reply on Problem Binding Vue Variable

Perhaps Vue expects the option tags to have a value attribute?

<select v-model="test">
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
</select>
<span>@{{test}}</span>

Edit: Nevermind, this is working now: https://codepen.io/anon/pen/xpJvze

12 Dec
1 year ago

jbloomstrom left a reply on ERR_CONNECTION_REFUSED On Chrome But Not Firefox, Or Safari

Check your proxy settings in Chrome. Firefox can ignore system proxy settings, but Chrome uses the system proxy by default.

jbloomstrom left a reply on Best Practice - Local Environment And Production Environment

@zaster Snapey is correct. To avoid being surprised by a new, possibly incompatible version of a package I always run composer update in my dev environment and thoroughly vet the updates (e.g. run my test suite). I have composer install in my deployment script to ensure that only tested versions of packages end up in production. Hope this helps.

01 Dec
1 year ago

jbloomstrom left a reply on Losing This Scope While In Component Method.

You could also use es6 arrow syntax.

createToken() {
    console.log(this.stripeEmail);
    
    this.stripe.createToken(this.card).then( result => {
        if (result.error) {
            // Inform the user if there was an error
            var errorElement = document.getElementById('card-errors');
            errorElement.textContent = result.error.message;
        } else {
            // This should show the email now
            console.log(this.stripeEmail);
        }
    });
}
25 Oct
1 year ago

jbloomstrom left a reply on Data Tampering Prevention

You're right. I forgot to add the part for updating the middleware group. I've updated the answer.

jbloomstrom left a reply on Pagination Unavailable When Filter Function Is Used

Does it work without the filter() part?

jbloomstrom left a reply on Best Caching Solution?

Some things to consider. If you haven't already, try out your site with DebugBar. It can help reveal the cause of slowness (slow queries (caching will help), too many queries (eager loading could help), etc.). You can find it here. https://github.com/barryvdh/laravel-debugbar

For caching, I personally use Redis. It's pretty straightforward to get set up, and there are some helpful videos here to help you get started.

jbloomstrom left a reply on Pagination Unavailable When Filter Function Is Used

In your search method in the controller, the $prices variable is not defined anywhere.

jbloomstrom left a reply on Import Excel File To Database With Mapping Each Field Dynamicaly

FYI, PHP has a native function for parsing CSV to Array.

http://php.net/manual/en/function.str-getcsv.php


$csv = array_map('str_getcsv', file('data.csv'));

jbloomstrom left a reply on VueJS Multi Language Inputs

Do you have any code you can share as a starting point?

jbloomstrom left a reply on Get All Entries Created At Specific Date

Consider querying all the deposits at once and then using a group function to group by day. It will ease the load on your database to do it all in one query. Like this:


// get all the deposits for the last month
$all_deposits = Deposit::where('created_at','>',Carbon::now()->subMonth())->get();

// now group by the created date
$all_deposits->groupBy( function($deposit) {
    return $deposit->created_at->format('Y-m-d');
});
16 Oct
1 year ago

jbloomstrom left a reply on DNS Issues With Nginx And .money TLD

OP seemed concerned about the time it took for propagation. I was simply sharing my experience.

13 Oct
1 year ago

jbloomstrom left a reply on Passing Data To Components

Friendly tip, you're more likely to get replies if you wrap your code blocks with 3 backticks `

Is this what you're looking for?

<tr v-for="(tipo, index) in listaOrdenada"> 
    <td @click="selected">{{ tipo.descricao }}</td>
</tr>

<app-formulario :campos="lista[index].tipo_registro_campos"></app-formulario>

jbloomstrom left a reply on DNS Issues With Nginx And .money TLD

FWIW, I have been using Route53 to host my DNS for some time now. Propagation takes mere minutes usually.

10 Oct
1 year ago

jbloomstrom left a reply on Data Tampering Prevention

The approach I typically take is to make the id part of the API endpoint.

// routes/api.php
Route::delete("posts/{post}", "[email protected]");

Then set up route model binding. https://laravel.com/docs/5.5/routing#route-model-binding

...
// RouteServiceProvider
public function boot()
{
    parent::boot();

    Route::model('post', App\Post::class);
}

Then protect your API routes with the api middleware to make sure only logged in users can access those routes.

// app/Http/Kernel.php
$middlewareGroups = [
    ...

    'api' => [
        'throttle:60,1',
        'bindings',
        'auth:api', // add this if only authenticated users can access the api
    ],
]


// RouteServiceProvider.php
...
   /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

Then use a Policy to see if the user is allowed to perform the operation on the given post. https://laravel.com/docs/5.5/authorization

// PostPolicy.php

...
   /**
     * Determine if the given post can be deleted by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function delete(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }

Register the policy

// AuthServiceProvider
...

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class,
    ];
...

Now you can authorize the delete in the controller:

// PostController.php
...
class PostController extends Controller
{
    /**
     * Delete the given blog post.
     *
     * @param  Request  $request
     * @param  Post  $post
     * @return Response
     */
    public function delete(Request $request, Post $post)
    {
        $this->authorize('delete', $post);

        // The current user can delete the blog post...
    }
}
28 Sep
1 year ago

jbloomstrom left a reply on Relationship Properties Are Not Visible?!

if you want to always return the children, you can set the $with property on the model.


// Category.php

class Category extends Model {

    ...
    protected $with = [
        'children'
    ];
    ...
}

Or if you want to get deeply nested relationships, you can use dot notation:


// Category.php

class Category extends Model {

    ...
    protected $with = [
        'children.children.children.children' // will get children 4 layers deep
    ];
    ...
}

jbloomstrom left a reply on How Can I Session-out & Logout - When IP Address Is Changed ?

I would add a last_known_ip column to my user model. I would then make a custom middleware that compares the current ip to the last_known_ip. If they match, then proceed, else destroy session and logout.

function getRealUserIp(){
    switch(true){
      case (!empty($_SERVER['HTTP_X_REAL_IP'])) : return $_SERVER['HTTP_X_REAL_IP'];
      case (!empty($_SERVER['HTTP_CLIENT_IP'])) : return $_SERVER['HTTP_CLIENT_IP'];
      case (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) : return $_SERVER['HTTP_X_FORWARDED_FOR'];
      default : return $_SERVER['REMOTE_ADDR'];
    }
 }

jbloomstrom left a reply on Relationship Properties Are Not Visible?!

Can you post your migration too? In short, you want to store the parent_id on the category model, not the children.

class Category extends Model {
    ...
    protected $fillable = [
        'name',
        'parent_id'
    ];
    ...
}

// migration

    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->unsignedInteger('parent_id')->nullable();
        $table->timestamps();
    });

jbloomstrom left a reply on Laravel API

I wouldn't have users pass their password in the request url. I would instead look at using api tokens. Here is a good article to get you started if you don't want to use passport. https://gistlog.co/JacobBennett/090369fbab0b31130b51

26 Sep
1 year ago

jbloomstrom left a reply on Compile JavaScript To IE11 (ES5?)

@EmilMoe Laravel Mix does this automatically when you call mix.js(...).

21 Sep
1 year ago

jbloomstrom left a reply on Inject Content In Component From Other Component

This is my preferred method of communicating between Vue components. Check out the global event bus pattern. https://alligator.io/vuejs/global-event-bus/

jbloomstrom left a reply on Vue Connecting To Laravel API

This is a common error. It's called CORS - Cross-Origin Resource Sharing. It's blocked by most servers as a security feature and has to be explicitly allowed to avoid getting the error. This package can help you get Laravel configured to allow it. https://github.com/barryvdh/laravel-cors

jbloomstrom left a reply on How Do I Pass A Variable Of Data From One File To Another File?

The best way that I have found to communicate between components is to use a "Bus" instance of Vue. Then you Bus.$emit an event from one component and Bus.$on listen for it on another component. https://alligator.io/vuejs/global-event-bus/


// app.js
...
window.Bus = new Vue();
...

// product.vue

...

methods : {
    updateCart() {
        Bus.$emit('UpdateCartData', { payload : { SOME_DATA_HERE } });
    }
},

...

// header.vue
...

mounted() {
    this.listen();
},

methods : {
    listen() {
        Bus.$on('UpdateCartData', (event) => {
            this.update(event.payload);
        });
    }
}
...

jbloomstrom left a reply on Use Bolean In Computed

You don't need to create a custom accessor just to cast to a boolean, you can use the $casts property on the model.

// your <model>.php file
...

protected $casts = [
    'published' => 'bool',
];
...

jbloomstrom left a reply on Shift Time Calculation Based On Given Times

Have you looked at Carbon? It has tons of useful methods for calculating the difference between dates. Also are you able to access a full datetime for these calculations?

$start = Carbon::parse('2017-09-21 08:00:00');
$finish = Carbon::parse('2017-09-21 17:00:00');

$finish->diff($start)->format('%H:%I:%S');
// 09:00:00