jbloomstrom

jbloomstrom

Programmer Analyst at Matanuska-Susitna Borough

Member Since 4 Years Ago

Palmer

Experience Points
147,055
Total
Experience

2,945 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
1253
Lessons
Completed
Best Reply Awards
40
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 30
147,055 XP
Apr
22
1 month ago
Activity icon

Commented on Refactoring For Flexibility

Another way to reduce indentation is to filter the attributes before iterating over them.


Array.from(el.attributes)
    .filter(attribute => attribute.name.startsWith('@'))
    .forEach(attribute => {
	let event = attribute.name.replace('@','')
        el.addEventListener(event, () => {
            eval(`with (data) { (${attribute.value}) }`)
        })
    });
Apr
15
1 month ago
Activity icon

Awarded Best Reply on Help With Database Issue: Integrity Constraint Violation.

The problem seems to be that it's attempting to insert a row into the activities table for the deleted project, but activities requires a project_id of a valid project. There are a few approaches you could take to fix this--it just depends on what your requirements are for tracking activities for projects.

If you want to be able to record activity for deleted projects, I would suggest using soft deletes on your Project model.

That way the project will stay in the database to satisfy the foreign key requirement in the activity table.

https://laravel.com/docs/7.x/eloquent#soft-deleting

Another approach would be to make project_id nullable in your activities table. Then use onDelete('set null') on the project_id foreign key.

$table->unsignedBigInteger('project_id')->nullable();
...
$table->foreign('project_id')->references('id')->on('projects')->onDelete('set null');

Another approach would be to not have deleted in your recordableEvents on the Project model.

// Project model
/**
 * Model events that should trigger new activity.
 *
 * @var array
 */
protected static $recordableEvents = ['created', 'updated'];
Apr
14
1 month ago
Activity icon

Replied to Ranks/Levels To Users

What you pass into withCount should be the name of a relationship defined on the User model.

// User model

public function paid_orders()
{
    return $this->hasMany(Order::class)->where('paid',true);
}

// your controller, etc.
User::withCount('paid_orders')->orderBy('paid_orders_count','desc')->get();

Activity icon

Replied to Help With Database Issue: Integrity Constraint Violation.

The problem seems to be that it's attempting to insert a row into the activities table for the deleted project, but activities requires a project_id of a valid project. There are a few approaches you could take to fix this--it just depends on what your requirements are for tracking activities for projects.

If you want to be able to record activity for deleted projects, I would suggest using soft deletes on your Project model.

That way the project will stay in the database to satisfy the foreign key requirement in the activity table.

https://laravel.com/docs/7.x/eloquent#soft-deleting

Another approach would be to make project_id nullable in your activities table. Then use onDelete('set null') on the project_id foreign key.

$table->unsignedBigInteger('project_id')->nullable();
...
$table->foreign('project_id')->references('id')->on('projects')->onDelete('set null');

Another approach would be to not have deleted in your recordableEvents on the Project model.

// Project model
/**
 * Model events that should trigger new activity.
 *
 * @var array
 */
protected static $recordableEvents = ['created', 'updated'];
Activity icon

Replied to Ranks/Levels To Users

Check out the docs for withCount. It does exactly what you are describing. https://laravel.com/docs/7.x/eloquent-relationships#counting-related-models

Activity icon

Replied to Ranks/Levels To Users

I'm making some assumptions about how your models and migrations are set up, so tweak to fit your specific situation.

// using collection sortByDesc
$ranked = User::withCount('orders')->get()
	->sortByDesc('orders_count');

// using sql orderBy
$ranked = User::withCount('orders')->orderBy('orders_count','desc')->get();

// the rank is the index of each row in the collection plus 1
$ranked->each( function($user, $index) {
	$rank = $index+1;
	// continue from here
});
Activity icon

Commented on Build A Like/Dislike System

Sometimes I like to assign a temporary variable if I need to pass a hard-coded value into a function.

in this case, the intent is pretty obvious, so the temporary variable is a little superfluous.

$this->like($user,$liked=false);

in this case, it's not obvious what 1500 means, so the temporary variable adds clarity.

$user->invoiceFor($cents=1500, "Laracasts subscription");
Activity icon

Awarded Best Reply on ErrorException Getimagesize(avatar/about.jpg): Failed To Open Stream: No Such File Or Directory

I'm fairly certain storeAs only returns the relative path of the file. You can use the asset helper to get the full path.

Try something like this:

...
$imagesize = getimagesize( asset("storage/" . $upload) );
...

https://laravel.com/api/7.x/Illuminate/Http/UploadedFile.html#method_storeAs

https://laravel.com/docs/7.x/filesystem#the-public-disk

Apr
13
1 month ago
Activity icon

Awarded Best Reply on Property [purchase_number] Does Not Exist On This Collection Instance.

You are setting $purchase to a collection of purchases, not an individual purchase. You need to pass in the purchase_number or another way of identifying which purchase to grab.

/** Return invoice for the particular order in PDF format**/

   public function invoice($purchaseNum){
    // Get user.
   // $user = User::find(Auth::user()->id);
    $user = Auth()->user(); 
    //$purchase = $user->purchases;
    $purchase = $user->purchases()
        ->where('purchase_number',$purchaseNum)->first();
    $pdf = PDF::loadView('documents.invoice',compact('purchase'))
        ->setPaper('A4');
    return $pdf->stream('invoice.pdf');
   }

Activity icon

Replied to Property [purchase_number] Does Not Exist On This Collection Instance.

You are setting $purchase to a collection of purchases, not an individual purchase. You need to pass in the purchase_number or another way of identifying which purchase to grab.

/** Return invoice for the particular order in PDF format**/

   public function invoice($purchaseNum){
    // Get user.
   // $user = User::find(Auth::user()->id);
    $user = Auth()->user(); 
    //$purchase = $user->purchases;
    $purchase = $user->purchases()
        ->where('purchase_number',$purchaseNum)->first();
    $pdf = PDF::loadView('documents.invoice',compact('purchase'))
        ->setPaper('A4');
    return $pdf->stream('invoice.pdf');
   }

Activity icon

Replied to ErrorException Getimagesize(avatar/about.jpg): Failed To Open Stream: No Such File Or Directory

I'm fairly certain storeAs only returns the relative path of the file. You can use the asset helper to get the full path.

Try something like this:

...
$imagesize = getimagesize( asset("storage/" . $upload) );
...

https://laravel.com/api/7.x/Illuminate/Http/UploadedFile.html#method_storeAs

https://laravel.com/docs/7.x/filesystem#the-public-disk

Activity icon

Replied to Invalid Route Action,why?

Can you post your routes file(s)? Looks like you have a route that expects your controller to be invokable (i.e. a single-action controller).

Activity icon

Awarded Best Reply on Pass From Parent To Child To Custom Component

When you use v-bind:message or the shorthand :message, you are telling vue to interpret what's between the quotes as javascript-- i.e. a variable named body test, which is invalid javascript.

To bind the string "body test" to message, leave off the colon like this message="body test". It will then be passed like a regular html attribute.

Hope this helps.

Activity icon

Replied to Searching Related Tags

Split the question string into an array of words, then reject any stopwords (common words that don't contribute to the search). Run the remaining words through a stemming utility to get related words (i.e. print becomes ['print','printer','printing','printed']) then compare the result with your existing tags.

Something like this, (untested)

$stopWords = new StopWords();
$stopWords->getStopWordsFromLanguage('en');

$tags_to_search_for = collect(explode(' ',$question))
    ->reject( function($word) use ($stopwords) {
	return in_array($word, $stopwords)
    })
    ->map( function($word) {
	return \Nadar\Stemming\Stem::stem($word, 'en');
    })
    ->collapse();

$builder = Question::query();

$tags_to_search_for
    ->each ( function($word) use ($builder) {
	return $builder->orWhere("tags","like","%{$word}%");
    });

$related_questions = $builder->get();

see

Activity icon

Replied to Pass From Parent To Child To Custom Component

When you use v-bind:message or the shorthand :message, you are telling vue to interpret what's between the quotes as javascript-- i.e. a variable named body test, which is invalid javascript.

To bind the string "body test" to message, leave off the colon like this message="body test". It will then be passed like a regular html attribute.

Hope this helps.

Apr
09
1 month ago
Activity icon

Replied to Check Id In Collection

Maybe try the contains method on the collection.

https://laravel.com/docs/7.x/collections#method-contains

@if ( $forms->pluck('id')->contains($lead->forms_id) )
  {{ $forms->firstWhere('id',$lead->forms_id)->name }}
@endif
Activity icon

Replied to Laravel + DigitalOcean Spaces Rate Limits

I assume they are talking about "zipping" up groups of images for upload to reduce the number of uploads. You could then extract the zip files from the server to their destination folder.

Activity icon

Awarded Best Reply on Migration Error: 1215 Cannot Add Foreign Key Constraint

The replies table definitely needs to be created first, otherwise the foreign key constraint will fail.

Try adding the foreign key in another step, like this:

Schema::create('threads', function (Blueprint $table) {
    $table->increments('id');
    $table->string('slug')->unique()->nullable();
    $table->unsignedInteger('user_id');
    $table->unsignedInteger('channel_id');
    $table->unsignedInteger('replies_count')->default(0);
    $table->unsignedInteger('visits')->default(0);
    $table->string('title');
    $table->text('body');
    $table->unsignedBigInteger('best_reply_id')->nullable();
    $table->timestamps();
});

Schema::table('threads', function(Blueprint $table) {
    $table->foreign('best_reply_id')
        ->references('id')
        ->on('replies')
        ->onDelete('set null');
});

(edit)

Your replies table should have a bigIncrements primary key to match the unsignedBigInteger foreign key

Schema::create('replies', function (Blueprint $table) {
    //$table->increments('id');
    $table->bigIncrements('id');
    $table->unsignedInteger('user_id');
    $table->unsignedInteger('thread_id');
    $table->text('body');
    $table->timestamps();
});
Activity icon

Replied to Migration Error: 1215 Cannot Add Foreign Key Constraint

The replies table definitely needs to be created first, otherwise the foreign key constraint will fail.

Try adding the foreign key in another step, like this:

Schema::create('threads', function (Blueprint $table) {
    $table->increments('id');
    $table->string('slug')->unique()->nullable();
    $table->unsignedInteger('user_id');
    $table->unsignedInteger('channel_id');
    $table->unsignedInteger('replies_count')->default(0);
    $table->unsignedInteger('visits')->default(0);
    $table->string('title');
    $table->text('body');
    $table->unsignedBigInteger('best_reply_id')->nullable();
    $table->timestamps();
});

Schema::table('threads', function(Blueprint $table) {
    $table->foreign('best_reply_id')
        ->references('id')
        ->on('replies')
        ->onDelete('set null');
});

(edit)

Your replies table should have a bigIncrements primary key to match the unsignedBigInteger foreign key

Schema::create('replies', function (Blueprint $table) {
    //$table->increments('id');
    $table->bigIncrements('id');
    $table->unsignedInteger('user_id');
    $table->unsignedInteger('thread_id');
    $table->text('body');
    $table->timestamps();
});
Activity icon

Replied to Set Key On An Array If It Does Not Exist

You have to take special care when dealing with arrays to make them reactive. Check out this page for more info.

When you modify an Array by directly setting an index (e.g. arr[0] = val) or modifying its length property [Vue.js] cannot pickup these changes. Always modify arrays by using an Array instance method, or replacing it entirely. Vue provides a convenience method arr.$set(index, value) which is syntax sugar for arr.splice(index, 1, value).

Further reading: Reactivity in Depth and Array Change Detection.

Apr
08
1 month ago
Activity icon

Commented on Build The Explore Users Page

ExploreController seems like a good use case for an invokable controller.

Apr
06
1 month ago
Activity icon

Replied to Sort On Properties Of 2 Different Foreign Keys In Laravel

Looks like you need to use join to do the sorting you want. Should still be able to use with too.

This should get you close.

User::with(['start_date','end_date'])
    ->join('themes as end_theme','users.end_theme_id','=','end_theme.id')
    ->join('themes as start_theme','users.start_theme_id','=','start_theme.id')
    ->orderBy('end_theme.end','desc')
    ->orderBy('start_theme.start','desc')
    ->orderBy('users.name','asc')
    ->get();

Check out this reply for reference

Activity icon

Commented on Making Things Reactive

Good video. FYI, it's showing Jeffrey's bio instead of Caleb's.

Mar
19
2 months ago
Activity icon

Replied to Keyup.enter Closing Modal

Are you preventing the default form submit behavior?

<form v-on:submit.prevent ...
Activity icon

Replied to Vue Terminology

There is a free course on Laracasts too. https://laracasts.com/series/learn-vue-2-step-by-step

Mar
10
2 months ago
Activity icon

Replied to Sample Code Containing Expression Like {{ $title }} Cause Blank Page In Laravel

@ziaakbari Are you working in a blade file? If you want blade to ignore the template string so Vue or Angular will interpret it, you need to use an @ symbol before the {{. Not sure if this helps.

  <li v-for="item in items" :key="item.id">
   @{{ item.name}}
  </li>
Feb
20
3 months ago
Activity icon

Replied to Modal Delete Confirmation With BootstrapVue

Have you considered a global event bus? Basically, a separate Vue instance that acts as a go-between to allow events to be emitted and listened by disparate components.

https://alligator.io/vuejs/global-event-bus/

Activity icon

Replied to Validation Rules For Field Allowable Null And String

Have you tried sometimes?

Something like this:

'started_at' => [
    'sometimes',
    'required',
    'string',
    'date_format:Y-m-d H:i:s',
    new EmploymentStartDateCanBeChanged($this->route('referee'))
]

To prevent it invalidating null values, you'll need to conditionally disable the started_at field. Check out this answer for more on how to do that. https://laracasts.com/discuss/channels/laravel/validation-sometimesrequired?page=1#reply=510966

Here's a codepen of a working example. https://codepen.io/anon/pen/eadXox

https://laravel.com/docs/5.8/validation#conditionally-adding-rules

Jan
30
4 months ago
Activity icon

Awarded Best Reply on How To Add Dynamically Post Slug To Facebook Like Button?

In attribute values, you need to use the v-bind: directive. Something like this:

v-bind:data-href="`https://test.com/post/${post.slug}`"

or you can use the shorthand :

:data-href="`https://test.com/post/${post.slug}`"

https://vuejs.org/v2/guide/syntax.html#Attributes

Activity icon

Replied to How To Add Dynamically Post Slug To Facebook Like Button?

In attribute values, you need to use the v-bind: directive. Something like this:

v-bind:data-href="`https://test.com/post/${post.slug}`"

or you can use the shorthand :

:data-href="`https://test.com/post/${post.slug}`"

https://vuejs.org/v2/guide/syntax.html#Attributes

Jan
23
4 months ago
Activity icon

Replied to How Do I Override The 404 For The Resource Controller?

Check out this tutorial. It explains how to use custom handling if the route can't find a model.

TLDR:

// RouteServiceProvider.php
$router->model('code', App\Code::class, function () {
    // throw new NotFoundHTTPException;
    // your custom logic here.
});

https://scotch.io/tutorials/cleaner-laravel-controllers-with-route-model-binding#toc-custom-exceptions-for-route-model-binding

Activity icon

Awarded Best Reply on Polymorphic View Assistance

I think you're on to a good approach, dynamically include a partial specific to the reviewable_type. You could even add a trait to each reviewable model to simplify getting the partial name.

// trait added to Post, Comment, Picture etc.
use Illuminate\Support\Str;

trait CanGetReviewableTypePartialName {
  
  function getPartialNameAttribute() {
    // insert your own naming convention
   
    return "partials._" . Str::snake( class_basename( $this->reviewable ) );
    // App\Post becomes partials._post
    // App\PostPicture becomes partials._post_picture
  }
}


// your blade template

@foreach($rows as $row)
@include($row->partial_name, ['reviewable' => $row->reviewable])
@endforeach

Activity icon

Replied to How Do I Sum Every N Rows In Laravel Using MySQL Queries?

Please format your code by placing three backticks ` before and after the code block like this:

```

code

```

With collections, you can break up results into groups of N rows each with the chunk method. https://laravel.com/docs/5.8/collections#method-chunk

You could then use reduce to process and derive a single value for each chunk. Or if you're wanting something other than a single value, you can use transform and apply whatever logic you want to each chunk.

https://laravel.com/docs/5.8/collections#method-reduce

https://laravel.com/docs/5.8/collections#method-transform

Activity icon

Replied to Polymorphic View Assistance

I think you're on to a good approach, dynamically include a partial specific to the reviewable_type. You could even add a trait to each reviewable model to simplify getting the partial name.

// trait added to Post, Comment, Picture etc.
use Illuminate\Support\Str;

trait CanGetReviewableTypePartialName {
  
  function getPartialNameAttribute() {
    // insert your own naming convention
   
    return "partials._" . Str::snake( class_basename( $this->reviewable ) );
    // App\Post becomes partials._post
    // App\PostPicture becomes partials._post_picture
  }
}


// your blade template

@foreach($rows as $row)
@include($row->partial_name, ['reviewable' => $row->reviewable])
@endforeach

Activity icon

Replied to 1 To M Query

@zaster Happy to help!

Activity icon

Replied to Re-Connect Old Forge Server To Laravel Forge

Is it not available from the Archived Servers page? If it's there, you can reconnect it with the current SSH key.

Activity icon

Awarded Best Reply on 1 To M Query

Something like this?

Job::whereHas('subjobs', function($query) use ($user_id, $company_id, $comp) {
  return $query->where('user_id', $user_id)
    ->where('user_company_id', $company_id)
    ->where('comp', $comp);
});

I'm making some assumptions about how your Job model is set up. If you post your full models, I can give a more accurate answer.

Activity icon

Replied to 1 To M Query

Something like this?

Job::whereHas('subjobs', function($query) use ($user_id, $company_id, $comp) {
  return $query->where('user_id', $user_id)
    ->where('user_company_id', $company_id)
    ->where('comp', $comp);
});

I'm making some assumptions about how your Job model is set up. If you post your full models, I can give a more accurate answer.

Jan
20
4 months ago
Activity icon

Replied to Querying On Relation Column Within A Relationship

hasMany returns a Builder instance, so you can chain a whereclause off it.

public function supplierThreads()
{
    return $this->hasMany(SupplierThread::class)
        ->where('status', '!==', 'closed');
}

public function supplierArchives()
{
    return $this->hasMany(SupplierThread::class)
        ->where('status', 'closed');
}
Jan
09
4 months ago
Activity icon

Replied to Can't Sync Many To Many Relation

Sounds like you may have missed some parentheses. There is a subtle but important difference between $Estado->requisitos and $Estado->requisitos(). The first one represents the Eloquent Collection, the second one returns the (BelongsToMany) relationship. The sync method is on the relationship, not the Eloquent Collection.

Activity icon

Replied to Can't Sync Many To Many Relation

You're trying to sync a collection to a collection, but you need to sync at the individual model level.

Search for the "syncing" example in the docs. You can see that it's meant to sync one model with many models.

$user->roles()->sync([1, 2, 3]);

For your example, try changing this:

$Estados->requisitos()->sync($requisitos);

to this:

$Estados->each->requisitos()->sync($requisitos);

It's a concept called higher order messaging

Another way of doing it would be:

$Estados->each(function($Estado) use ($requisitos) {
    $Estado->requisitos()->sync($requisitos);
});

Higher order messaging reads cleaner to me, so I use it whenever possible.

Dec
27
5 months ago
Activity icon

Replied to Message: Call To A Member Function Save() On Null

Try changing this:

 $ind->utili()->save($utili);

to this:

$utili->save();
Activity icon

Replied to Aws S3

You can pass the disk name as the second argument to the store method.

Like this:

$upload->store('images/task/medias', 's3');

From https://laravel.com/docs/5.8/filesystem#file-uploads

Activity icon

Replied to Eloquent Collection Heisenbug: Trying To Get Property Of Non-object!

I wonder if it's an issue of stale data.

What happens if you try getting a fresh instance of $otherOrgJob from the db? Like this?

$otherOrgJob->fresh()->jobParticipants->first()->id
Activity icon

Commented on Explain How To Limit Downloads Per User

Late to the party, but check out Firefox Developer Edition. https://www.mozilla.org/en-US/firefox/developer/