JoeDawson

JoeDawson

Member Since 5 Years Ago

Benfleet, Essex

Experience Points 82,410
Experience Level 17

2,590 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 365
Lessons
Completed
Best Reply Awards 91
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.

26 Jul
1 month ago

JoeDawson left a reply on Using WhereHas To Return Results Where ALL Relations Match?

Sussed it after stumbling across this this: https://stackoverflow.com/questions/32639091/laravel-eloquent-wherehas-with-all-items-in-relation

$recipes = Recipe::latest()->whereDoesntHave('ingredients', function(Builder $query) {
    $query->where('buying_current', false);
})->whereDoesntHave('resultants', function(Builder $query) {
    $query->where('selling_current', false);
})->get();

JoeDawson left a reply on Using WhereHas To Return Results Where ALL Relations Match?

@mstrauss thanks for your reply, didn't realise I had a response lol.

That unfortunately didn't work either, if it helps - here are my relations on my Recipe model.

/**
 * Resultants
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function resultants()
{
    return $this->belongsToMany(Item::class, 'recipe_resultant', 'recipe_id', 'resultant_id')
                ->withPivot('quantity');
}

/**
 * Ingredients
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function ingredients()
{
    return $this->belongsToMany(Item::class)->withPivot('quantity');
}
15 Jul
2 months ago

JoeDawson started a new conversation Using WhereHas To Return Results Where ALL Relations Match?

Hello,

I currently have the following query:

$recipes = Recipe::latest()->whereHas('ingredients', function(Builder $query) {
    $query->where('buying_current', true);
})->whereHas('resultants', function(Builder $query) {
    $query->where('selling_current', true);
})->get();

This query returns all recipes where at least one of the ingredients has a buying_current of true and a resultant has a selling_current of true.

What I would like to do, is fetch all recipes where ALL of the ingredients have a buying_current of true and ALL resultants have a selling_current of true too.

Rather than just returning recipes that have at least one of each. How can I achieve this?

Thanks in advance.

17 Jun
2 months ago

JoeDawson started a new conversation How Can I Structure My Database?

Hello,

I currently have a table of items that can be combined to create another item.

Here's an example:

  • Potion - 1 Dose
  • Potion - 2 Dose
  • Potion - 3 Dose

An example combination could be combining a 1 and 2 dose together to create a 3 dose.

I would like to be able to create a relation between these items but I'm unsure of the best way to store this info.

Do I create a table for "recipes" that contains a column for "ingredients" which contains ID's to my items.

  • id (incrementing id)
  • ingredients (list of ids)
  • item_id (unsigned int, ref's id on "items")

Or would you create a many to many style table?

  • ingredient_id (unsigned int, ref's id on "items")
  • item_id (unsigned int, refs id on "items") - the end item

I also need to be able to see what combined items will provide the cheapest way to the "end" item, so to speak.

Items tabel contains:

  • id
  • name
  • price
29 Nov
9 months ago

JoeDawson started a new conversation Using PutFileAs With An External File?

Hello,

I'm looking to store an external file using putFileAs however I'm having some trouble.

Is it even possible? putFileAs accepts a File object as it's second argument - however I don't have a "file" so to speak.

$image = Storage::putFileAs(
    'images',
    'http://path.to/some/external/image.jpg',
    str_random() . '.jpg'
);

What's my alternative?

Thanks!

16 Oct
10 months ago

JoeDawson left a reply on Route [customer.addProductPricing] Not Defined.

Can you should us your registered routes?

13 Aug
1 year ago

JoeDawson started a new conversation How Can I Improve This?

Hello,

I currently have the following code to update an Artist in my application.

$artist->fill($request->except('avatar'));

if($request->input('attributes.links.twitter.name'))
{
    $t = Twitter::getUsersLookup([
        'screen_name' => $request->input('attributes.links.twitter.name')
    ]);

    $artist->attributes->set('links.twitter.id', $t[0]->id);
} else {
    $artist->attributes->set('links.twitter.id', null);
}

$artist->save();

if ($request->has('avatar'))
{
    $artist->clearMediaCollection('avatars')
           ->addMediaFromRequest('avatar')
           ->preservingOriginal()
           ->toMediaCollection('avatars');
}

It's also pretty much the same when you create an artist too (except I obviously don't have an artist yet).

$artist = Artist::create($request->except('avatar'));

if($request->input('attributes.links.twitter.name'))
{
    $t = Twitter::getUsersLookup([
        'screen_name' => $request->input('attributes.links.twitter.name')
    ]);

    $artist->attributes->set('links.twitter.id', $t[0]->id);
} else {
    $artist->attributes->set('links.twitter.id', null);
}

$artist->save();

if ($request->has('avatar'))
{
    $artist->clearMediaCollection('avatars')
           ->addMediaFromRequest('avatar')
           ->preservingOriginal()
           ->toMediaCollection('avatars');
}

I'm not super happy with this bit at the moment;

if($request->input('attributes.links.twitter.name'))
{
    $t = Twitter::getUsersLookup([
        'screen_name' => $request->input('attributes.links.twitter.name')
    ]);

    $artist->attributes->set('links.twitter.id', $t[0]->id);
} else {
    $artist->attributes->set('links.twitter.id', null);
}

$artist->save();

Any suggestions on how I can clean this up? It's possible that in the future there will be multiple "links" (i.e SoundCloud) that have their own way of fetching the ID associated with the username/handle provided.

Thanks in advance!

02 Aug
1 year ago

JoeDawson left a reply on Retrieve Data From Many To Many

Sorry I misread your question! @RonB1985's reply is the correct answer here :)

JoeDawson left a reply on Retrieve Data From Many To Many

You could simplify @lmxdev's suggestion by doing this;

$admins = User::whereHas('roles', function($query) {
   $query->where('id', 1);
})->get();

Since relying on your ID may be an issue. Assuming your roles have a name attribute, you could also do this.

$admins = User::whereHas('roles', function($query) {
   $query->where('name', 'admin'); // or whatever your admin name is
})->get();

You can even extra this logic into a query scope for your users to allow you to something like this.

// your user model...
function scopeWhereRole($query, $role) {
    return $query->whereHas('roles', function($query) use($role) {
       $query->where('name', $role);
    });
}

// in your controller...
$admins = User::whereRole('admin')->get();
01 Aug
1 year ago

JoeDawson left a reply on Using Where With Route::resource()?

Could you give some context on what you're trying to achieve? Usually this sort of logic would be in your controller.

05 Jul
1 year ago

JoeDawson left a reply on Need Some Help With A Join

Solved this by installing this package https://github.com/staudenmeir/eloquent-has-many-deep

Setup a Venues relation on the User

public function venues()
{
    return $this->hasManyDeep(Venue::class, [
        'area_user', Area::class
    ]);
}

I then setup the Entries relation on the User now I have a Venues relation

public function entries()
{
    return $this->hasManyDeep(Entry::class, [
        'area_user', Area::class, Venue::class
    ]);
}

Then updated my withIncompleteEntriesCount scope to.

public function scopeWithIncompleteEntriesCount($query)
{
    return $query->withCount(['entries as incomplete_entries_count' => function($q) {
        $q->incomplete();
    }]);
}

Exactly what I was after!

JoeDawson left a reply on Need Some Help With A Join

@martinbean hey Martin! Thanks for your reply. I wish I had the ability to do that, however users aren't related to entries since multiple users can submit the same entry.

User -> belongsToMany -> Area -> hasMany -> Venue -> hasMany -> Entry

Hope that makes sense?

JoeDawson started a new conversation Need Some Help With A Join

Hey guys,

Currently working on an application that allows users to submit entries for venues.

Entries are created automatically for users to fill out, however I'm working on some reporting to display how many incomplete entries a user has.

I want to fetch the number of incomplete entries for a user when they're listed too. I currently have the following code:

$users = User::withIncompleteEntriesCount()->get();

The withIncompleteEntriesCount() scope looks like this;

public function scopeWithIncompleteEntriesCount($query)
{
    return $query->join('area_user', 'users.id', '=', 'area_user.user_id')
                 ->join('areas', 'area_user.area_id', 'areas.id')
                 ->join('venues', 'areas.id', '=', 'venues.area_id')
                 ->join('entries', 'venues.id', '=', 'entries.venue_id')
                 ->where('status', 'Incomplete')
                 ->where('entries.deleted_at', null)
                 ->select(DB::raw('count(*) as incomplete_entries_count'), 'users.*')
                 ->groupBy('users.id');
}

Now, the query is calculating incomplete entries correctly - I'm just having an issue where users who do not have incomplete entries are not being included.

Just to be clear, a user isn't assigned to an entry (since multiple users will see the same incomplete entry).

  • A user can be assigned to multiple areas. Using the area_user pivot table.
  • An area is then selected for a Venue
  • An entry is then assigned to a venue

I needed to use a scope too since the users needed to be "sortable" by this number (using https://github.com/Kyslik/column-sortable)

Can anyone help me also include the users who do not have incomplete entries too? It's also possible that some users will not have any entries at all and I want those too.

Thanks in advance!

02 Oct
1 year ago

JoeDawson left a reply on Button Component Rendering Incorrectly Inside Email

Turned out to be because of indenting.

@if($email->responsable)
    @component('mail::button', ['url' => route('responses.create', $email)])
        Submit Response
    @endcomponent
@endif

Because I'm using Markdown, it's treating the indentation as code block so all I had to do was remove my indents.

@if($email->responsable)
@component('mail::button', ['url' => route('responses.create', $email)])
    Submit Response
@endcomponent
@endif

Except you can still indent inside of the component. Which I find odd.

27 Sep
1 year ago

JoeDawson started a new conversation Button Component Rendering Incorrectly Inside Email

Hi all,

I currently have the following for a markdown template.

@component('mail::message')
# Hello, {{ $user->forename }}

{{ $email->body }}

@if($email->responsable)
    @component('mail::button', ['url' => route('responses.create', $email)])
        Submit Response
    @endcomponent
@endif
@endcomponent

When the email is sent, the button component is displayed as HTML.

html

But if I remove the if statement around the button the button is rendered as normal.

@component('mail::message')
# Hello, {{ $user->forename }}

{{ $email->body }}

@component('mail::button', ['url' => route('responses.create', $email)])
    Submit Response
@endcomponent
@endcomponent

Any ideas why the button wouldn't be rendered correctly inside of an if statement?

Thanks in advance.

19 Sep
1 year ago

JoeDawson left a reply on How Can I Build This Package?

Thanks @ohffs, got it working. Appreciate the help!

JoeDawson left a reply on How Can I Build This Package?

@ohffs thank you very much for this, I'll take a look at some point today and hopefully implement. Appreciate your time!

15 Sep
2 years ago

JoeDawson left a reply on How Can I Build This Package?

Bumping this as have returned to the project.

I will be using Guzzle to make the API requests, it's just how I would go about creating some kind of "driver" implementation of this.

Where the provider is the driver in this case and when you perform a search it searches on the provider.

If anyone knows of a pretty simply "driver" like implementation with a package that would be really helpful.

Would I use an interface? I believe that's what I would need. How exactly could I implement this into a package.

A little stumped.

08 Sep
2 years ago

JoeDawson started a new conversation Getting Nested Relation?

Hello,

Probably a question answered plenty of times before but I can't seem to find any.

In my app, Users can follow Artists and Artists have videos.

I can currently get the users artists they're following by using $user->following etc.

What I want to do is get the videos of the artists the user is following.

I tried this.

$videos = $user->following->videos;

But I'm getting

Property [videos] does not exist on this collection instance.

How can I access the nested relation and get a collection from it? Similar to what I get with $user->following

Thanks in advance.

20 May
2 years ago

JoeDawson started a new conversation How Can I Build This Package?

Hi all,

I'm currently working on a project that requires interacting with a few different APIs. A good example would be searching for movies - my project is however not searching for movies.

I would ideally like to be able to do this:

MovieSearch::provider('imdb')->search('Home Alone')->get();

Is there a lesson here on Laracasts that could help me build a package like this or does anyone know of a good, clear example that I could reference - perhaps a package similar to the example above?

Thanks in advance!

21 Apr
2 years ago

JoeDawson left a reply on Does Anyone Use Sketch?

@peterlc yes you can use Sketch to design vector logos, but you're still somewhat limited in comparison to tools like Illustrator. Sketch is for designing web and mobile interfaces (preferably).

I use Sketch daily, would never go back to Photoshop for design.

JoeDawson left a reply on Laravel 5.4 - Compiling Assets

Does removing these fix it?

@include foundation-global-styles;
@include foundation-everything;
@include foundation-flex-classes;
@include foundation-flex-grid;

Are you not already including the entire Foundation library with this?

@import "node_modules/foundation-sites/scss/foundation";
03 Apr
2 years ago

JoeDawson left a reply on Pass Through ID When Using With And WhereHas?

Had to settle for this;

$forms = FormBuilder::processable()->scored()->select('id', 'name')->get();

foreach($forms as $form)
{
    $venues = Venue::reportable()
                   ->withAverageScore($this->from, $this->to, $form->id)
                   ->orderBy('average_score', 'desc')
                   ->get();

    $form->venues = $venues;
}

return $forms;
29 Mar
2 years ago

JoeDawson started a new conversation Pass Through ID When Using With And WhereHas?

Hey,

I currently have the following query:

$forms = FormBuilder::with(['venues' => function($q) {
    $q->whereHas('entries', function($q) {
        $q->complete()->submittedBetween($this->from, $this->to);
    })->withAverageScore($this->from, $this->to)->orderBy('average_score', 'desc');
}])->get();

What I need to do, is pass the ID of the FormBuilder when using the withAverageScore() scope.

Currently it accepts a "from" and "to" dates to generate an average score for venues of entries between these given dates.

This method does a join like this:

public function scopeWithAverageScore($query, $from = null, $to = null)
{
    return $query->leftJoin('entries', function($join) use($from, $to) {
        $join->on('venues.id', '=', 'entries.venue_id')
            ->where('submitted_at', '>=', $from)
            ->where('submitted_at', '<=', $to)
            ->where('score', '!=', 0);
        })
        ->selectRaw('venues.*, AVG(entries.score) AS `average_score`')
        ->groupBy('venues.id')
        ->havingRaw('AVG(entries.score) > 0');
}

The issue I'm having is that the above joins ignore the FormBuilder, so I'm thinking of trying to pass the id of the FormBuilder to the withAverageScore scope.

So potentially having something like this:

withAverageScore($this->from, $this->to, $formBuilderID)

But I'm not sure how to get the ID of the FormBuilder to do this, can anyone be of help?

Thanks in advance.

03 Mar
2 years ago

JoeDawson left a reply on Review This Please.

@concord I was able to log into your cPanel, get a professional.

Someone may take it, but I doubt it as your site appears to be very shady.

28 Feb
2 years ago

JoeDawson left a reply on Tracking Down 'Undefined Variable: User`

As @cronix says, try $post->user->name - note no $

26 Feb
2 years ago

JoeDawson left a reply on How To Count How Many Posts Created?

The reason you're always receiving 1 created is because you're reassigning your $affected variable each time you loop the data.

You'd need to do something like this which will increase the count every time you save a post.

$data = json_decode($res->getBody(), true);

// set the default affected count to zero
$affected = 0;

foreach ($data as $value)
{
    $post = Post::firstOrNew(['post_id' => $value['id']]);
    $post->save();

    // increase the affected count
    $affected++;
}

$count = isset($affected) ? count($affected) : '0';

session()->flash('message', $count . ' Posts Created!');
17 Feb
2 years ago

JoeDawson left a reply on Struggling With Getting Relation Multiple Levels Deep

Ended up adding a new column to entries table and will just store the formbuilder id when submitting new entries, have already updated all existing entries too for it to work.

Used a hasManyThrough.

public function clients()
{
    return $this->hasManyThrough('App\Client', 'App\Entry', 'builder_forms_id', 'id');
}

Thanks for the help anyway man.

JoeDawson left a reply on Struggling With Getting Relation Multiple Levels Deep

It's definitely related to this method on my FormBuilder model:

public function clients()
{
    return Client::whereHas('venues', function($q) {
        $q->whereIn('id', $this->venues->lists('id'));
    });
}

JoeDawson left a reply on Struggling With Getting Relation Multiple Levels Deep

@bashy hey mate, just tried that - getting this for some reason... :/

Call to undefined method Illuminate\Database\Query\Builder::with()

$key = 'dashboard.clients.forms.' . $this->from . '.' . $this->to;

$forms = Cache::remember($key, 60, function() {
    return FormBuilder::processable()->scored()->with(['clients.reportable' => function($q) {
        $q->whereHas('entries', function($q) {
            $q->submittedBetween($this->from, $this->to);
        });
    }])->get();
});

JoeDawson started a new conversation Struggling With Getting Relation Multiple Levels Deep

Hello,

I'm trying to set up a relation that is proving to be a little difficult. Here are my models, but in short - users will submit form entries for a venue.

  • FormBuilder (hasMany Form)
  • Form (belongsTo FormBuilder, hasMany Entry)
  • Clients (hasMany Venue)
  • Venues (belongsTo Client)
  • Entry (belongsTo Form, belongsTo Venue)

My current relations allow me to do the usual stuff like so:

// get the form builders forms...
$forms = $formBuilder->forms;

// get the entries from the forms...
$entries = $forms->first()->entries;

// get a clients venues
$venues = $client->venues;

What I'm trying to currently do, is get the clients from my form builders.

Now I do currently have a relationship set up to get my venues from a form builder using hasManyThrough:

//FormBuilder.php
public function venues()
{
    return $this->hasManyThrough('App\Venue', 'App\Form', 'form_id', 'id');
}

So this does allow me to get the venues from the form builder.

$formBuilder->venues;

Obviously meaning I can get the ids of those venues to eventually get down to something like this.

//FormBuilder.php
public function clients()
{
    return Client::whereHas('venues', function($q) {
        $q->whereIn('id', $this->venues->lists('id'));
    });
}

But when I try and use this, I also get this error.

$formBuilder = FormBuilder::with('clients')->first();

return $formBuilder;

Call to undefined method Builder::addEagerConstraints()

Now as I understand, I'm getting this error because this isn't a proper relationship and I just have a method to get the clients instead.

So really I should be using this.

$clients = FormBuilder::first()->clients()->get();

But this doesn't allow me to use the whereHas method on my FormBuilder. As my end goal is to achieve something like this.

FormBuilder::processable()->scored()->with(['clients' => function($q) {
    $q->reportable()->whereHas('entries', function($q) {
        $q->submittedBetween($this->from, $this->to);
    });
}])->get()

If anyone could help nudge me into the right direction I'd really appreciate it.

Many thanks

16 Feb
2 years ago

JoeDawson left a reply on Remove Items In Query When Using SelectRaw?

@Mittensoff using havingRaw('average_score > 0') was giving me an unknown column error.

I had to use this;

->havingRaw('AVG(entries.score) > 0')

Thanks for letting me know about havingRaw!

JoeDawson started a new conversation Remove Items In Query When Using SelectRaw?

Hello,

I have 3 models, a Client, Venue & Entry. A Client hasMany Venue and a Venue hasMany Entry.

Each entry has a score and my query below will return all Clients with their average score (based on the clients venues).

$query->join('venues', 'clients.id', '=', 'venues.client_id')
    ->leftJoin('entries', function($join) use($from, $to) {
        $join->on('venues.id', '=', 'entries.venue_id')
            ->where('submitted_at', '>=', $from)
            ->where('submitted_at', '<=', $to);
    })
    ->selectRaw('clients.*, AVG(entries.score) AS `average_score`')
    ->groupBy('clients.id');

I only want to retrieve the Clients where their score is greater than zero.

I've tried to use a where() after I get the average score, but obviously I'm getting a column does not exist error as average_score doesn't actually exist as I'm getting the average in the selectRaw.

Any ideas how I can omit the clients that have a score of zero?

14 Feb
2 years ago

JoeDawson left a reply on Find Country

Lots of GeoIP packages out there, I've used this in the past.

https://github.com/stevebauman/location

JoeDawson left a reply on OrderBy The WhereHas Count?

@SaeedPrez brilliant - thanks for clearing that up man. Appreciate your help :)

JoeDawson left a reply on OrderBy The WhereHas Count?

Hey @SaeedPrez,

So just use my whereHas query inside withCount?

$venues = Venue::reportable()->whereHas('entries', function($query) {
    $query->complete()->bluelight()->whereBetween('submitted_at', [$this->from, $this->to]);
})->withCount(['entries' => function($query) {
    $query->complete()->bluelight()->whereBetween('submitted_at', [$this->from, $this->to]);
}])->get()->sortBy('entries_count');

JoeDawson started a new conversation OrderBy The WhereHas Count?

Hello,

I have two models, Venue and Entry. Where a venue hasMany entry and where a entry belongsTo venue.

What I'm trying to do, is get all venues that have complete entries (also between two given dates) and sort/order these venues based on the number of complete entries they have.

Here's what I currently have;

$venues = Venue::reportable()->whereHas('entries', function($query) {
    $query->complete()->whereBetween('submitted_at', [$this->from, $this->to]);
})->withCount('entries')->get()->sortBy('entries_count');

At the moment, this does not return the correct entries_count - it gives me the TOTAL number of entries for that venue NOT just the entries that are complete - which is what I want.

So my question is - how can I order my venues based on the total number of complete entries this venue has?

Thanks in advance!

07 Feb
2 years ago

JoeDawson left a reply on Using Scopes After Queried?

I pass a Collection to DashboardService, I've just replicated the scopes I have into this class. For example here's a couple of them...

// App\Services\DashboardService.php

/**
 * Dashboard Service Instance
 * 
 * @param Collection $entries
 */
public function __construct(Collection $entries)
{
    $this->entries = $entries;
}

/**
 * Return all entries.
 * 
 * @return array
 */
public function all()
{
    return $this->entries;
}

/**
 * Return all of the training entries.
 * 
 * @return array
 */
public function training()
{
    return $this->entries->where('training', true);
}

JoeDawson left a reply on Using Scopes After Queried?

Ok so I'm not sure if this is necessarily the best way to do this, but I've created a class called DashboardService with a bunch of methods.

$from = $request->has('from') ? $request->get('from') : Carbon::now()->subMonth();
$to   = $request->has('to')   ? $request->get('to')   : Carbon::now();

$data = Entry::whereBetween('submitted_at', [$from, $to])->get();

$entries = new DashboardService($data);

return view('dashboard.index', compact('entries'));

In my view I use each one line this.

{{ $entries->all()->count() }}
{{ $entries->incomplete()->count() }}
{{ $entries->actionRequired()->count() }}
{{ $entries->pending()->count() }}
{{ $entries->processed()->count() }}
{{ $entries->training()->count() }}

Kind of clean I guess?

JoeDawson left a reply on Using Scopes After Queried?

@tykus I mentioned that groupBy wouldn't work here, see the training scope above... it's not scoped by the status.

JoeDawson left a reply on Using Scopes After Queried?

Sorry, the complete and incomplete scopes probably weren't the best examples. I have like 6 or 7 different scopes.

$entries = Entry::whereBetween('submitted_at', [$from, $to]);

return view('dashboard.index', compact('entries'));
{{ $entries->count() }} // i get this count
{{ $entries->incomplete()->count() }} // i do not get any of these...
{{ $entries->actionRequired()->count() }}
{{ $entries->pending()->count() }}
{{ $entries->processed()->count() }}
{{ $entries->bluelight()->count() }}
{{ $entries->training()->count() }}

JoeDawson left a reply on Using Scopes After Queried?

Can you use a scope with groupBy though? Some of the scopes I have like the completed() one doesn't actually check for say a status of "completed".

It's like this;

public function scopeComplete($query)
{
    return $query->where('status', '!=', 'Incomplete');
}

One of my other scopes is like this;

public function scopeTraining($query)
{
    return $query->where('training', true);
}

So I'm not sure if say something like groupBy('status') would work here. Still thinking lol...

JoeDawson started a new conversation Using Scopes After Queried?

Hello,

I'm sure I'm over thinking this and I'm sure there's an easier way to do this but my brain isn't working right now.

I'm working on a "Dashboard" to simply show the total number of entries based on a few different scopes.

The dashboard allows you to specify a date range, but if one isn't sent it shows the last month.

$from = $request->has('from') ? $request->get('from') : Carbon::now()->subMonth();
$to   = $request->has('to')   ? $request->get('to')   : Carbon::now();

$entries = Entry::whereBetween('submitted_at', [$from, $to])->get();

return view('dashboard.index', compact('entries'));

At the moment, I can display the total number of entries just fine.

$entries->count();

What I have though is a few (local) scopes for my Entry model that I want to use and also display this info. Firstly, I just tried to use them in my view - but obviously this wouldn't work as I already have a collection.

$entries->complete()->count();
$entries->incomplete()->count();
// etc...

I then tried omitting the ->get() from the Eloquent query above, but I get "method does not exist" errors as obviously my scopes aren't available from the builder.

How can I display the counts after this query? Surely I don't have to create a handful of different queries to do this?

I hope you can help me from losing my mind :)

20 Jan
2 years ago

JoeDawson left a reply on Laravel Mix Webpack Error

When I run the command node_modules/.bin/webpack

This isn't Laravel Mix. What does your gulpfile.js look like?

04 Jan
2 years ago

JoeDawson left a reply on Installing Laravel: Terminal Error After Install MacOS Sierra

Have you tried a new terminal window? When you change your bash profile, you need to start a new terminal instance before any changes are made.

22 Dec
2 years ago

JoeDawson left a reply on Foreach Loop, Addition To Get Total

{{ $accounts->sum('receipt_value') }}

Nevermind, @zachleigh had replied before I came back to this tab lol.