mstarkey

Senior Developer at TurnbullRipley

Experience

66,255

0 Best Reply Awards

  • Member Since 4 Years Ago
  • 720 Lessons Completed
  • 0 Favorites

27th October, 2017

mstarkey started a new conversation How Do I GroupBy More Than One Column? • 4 weeks ago

I am trying to run a groupBy on a collection using more than one column. currently I have this code:

$entries = TimesheetEntry::with('project','user','timesheet','client','timesheetTask')
                ->whereHas('project', function($q) use ($client_id){
                    $q->where('client_id', '=', $client_id);
                })
                ->whereBetween('updated_at', [$start, $end])
                ->get()->groupBy('project_id');

which returns a list of projects for a client and a total amount of hours per project, thats good, it does the job.

The issue starts when I want to be more granular, i.e. returning a list of tasks relating to each project, i.e.

project01 - design = 20hrs project01 - dev = 30hrs project02 - dev = 20hrs project03 - dev = 30hrs

If I use this code:

$entries = TimesheetEntry::with('project','user','timesheet','client','timesheetTask')
                ->whereHas('project', function($q) use ($client_id){
                    $q->where('client_id', '=', $client_id);
                })
                ->whereBetween('updated_at', [$start, $end])
                ->get()->groupBy('task_id');

the totals come up correct for the task but only displays the first project name. Odd right?

So I tried using and array of groups but that just doesn't work like so:

$entries = TimesheetEntry::with('project','user','timesheet','client','timesheetTask')
                ->whereHas('project', function($q) use ($client_id){
                    $q->where('client_id', '=', $client_id);
                })
                ->whereBetween('updated_at', [$start, $end])
                ->get()->groupBy('project_id','task_id');

any thoughts on this?

Thank

Mark

20th October, 2017

mstarkey left a reply on Calculate The Difference In Days From An Array • 1 month ago

The final answer is to add an extra day to the code like so:

$days = $items->reduce(function ($carry, $item) {
       return $carry + $item->start->diffInDays($item->end->addDay());
}, 0);

thanks to @ftrillo for an elegant solution to an irritating problem :)

mstarkey left a reply on Calculate The Difference In Days From An Array • 1 month ago

@ftrillo,

after some more testing I have discovered that the diffInDays returns 1 less that the the 2 dates indicated i.e.

Mon, Oct 23, 2017 12:00 AM to Fri, Oct 27, 2017 11:00 PM returns 4 not 5 as expected.

so the issue is not the 'reduce' function and is as suspected the diffInDays function.

I will keep digging, but thank you for your solution, it is the correct one to use in this case.

mstarkey left a reply on Calculate The Difference In Days From An Array • 1 month ago

for some reason each entry is minus 1

e.g. (4,5,2) returns a total of 8 not 11

I have tested with several difference datasets and the result is the same, its a weird one for sure, I am aware that the diffInDays returns an integer but wondering if the hours need to be full 24 to work correctly. I can't find anything in the nesbot/Carbon docs.

thanks

Mark

mstarkey left a reply on Calculate The Difference In Days From An Array • 1 month ago

Hi @ftrillo,

Thanks for you reply/solution. I applied it to my code and the results looked promising, a very elegant solution.

however the results are not what I was expecting and i think thats due to the reduce being used on the date->diffInDays calculations rather than a flat integer.

would a foreach return the same result or does the 'reduce function' wrap that into something more user friendly?

19th October, 2017

mstarkey started a new conversation Calculate The Difference In Days From An Array • 1 month ago

I am trying to calculate the amount of days from an array of start and end dates.

I can calculate the difference from one line using $item->start->diffInDays($item->end) but I need to produce an array of dates then add them together.

any thoughts are welcome on this.

many thanks

Mark

18th July, 2017

mstarkey left a reply on Property Does Not Exist On This Collection Instance. • 4 months ago

I am not sure this the 'right way' to do it, but it works none the less

The controller


$time = explode(" - ", $request->input('time'));
        $client_id = $request->input('client_id');
        $start = $this->change_date_format($time[0]);
        $end = $this->change_date_format($time[1]);

            $entries = TimesheetEntry::with('project')
                ->whereHas('project', function($q) use ($client_id){
                    $q->where('client_id', '=', $client_id);
                })
                ->whereBetween('updated_at', [$start, $end])
                ->get()->groupBy('project_id');

            return view('_modules.admin.reports.report', compact(
                'entries',
                'start',
                'end'
            ));

and the view

@foreach($entries as $item)
                    <tr>
                        <td>{{ $item[0]->project->client->name }}</td>
                        <td>{{ $item[0]->project->project_name }}</td>
                        <td>{{ $item->sum('mon_hrs') + $item->sum('tue_hrs') + $item->sum('wed_hrs') + $item->sum('thu_hrs') + $item->sum('fri_hrs') + $item->sum('sat_hrs') + $item->sum('sun_hrs') }}</td>
                    </tr>
 @endforeach

It took some thinking, and lots of research, but then what doesn't.

I think the docs need to include some blade examples of collection rendering as there is very little out there for this subject.

anyway, this is my best shot so far

mstarkey left a reply on Collections • 4 months ago

moving the the orderBy should help

public function treatmentsList()
    {
        $treatments_groups = Treatment::with('category')->where('status', 1)->orderBy('category.name', 'asc')->get()->groupBy('category.name');

        return view('pages.treatments.list', compact( 'treatments_groups'));
    }

The orderBy() need to be before the get() method and the groupBy() after, had the sam issue myself.

17th July, 2017

mstarkey left a reply on Property Does Not Exist On This Collection Instance. • 4 months ago

ok so the solution is as follows

ReportsController.php

public function report(Request $request)
    {
        $time = explode(" - ", $request->input('time'));
        $client_id = $request->input('client_id');
        $start = $this->change_date_format($time[0]);
        $end = $this->change_date_format($time[1]);

        $entries = TimesheetEntry::with('client','project','timesheetTask','timesheet')
            ->whereHas('project', function($q) use ($client_id){
                $q->where('client_id', '=', $client_id);
            })
            ->whereBetween('updated_at', [$start, $end])
            ->get();

        $items = $entries;
        return view('_modules.admin.reports.report', compact(
            'items',
            'start',
            'end'
        ));
    }

The reason for not using Carbon on the controller is down to preference and the fact I am using bootstrap datepicker and thats how the tutorial demonstrated it. I like an easy life at times :)

The whereHas method is a new addition as I found the data collection needed a more robust relationship and that meant removing the timesheet_entry/client relationship as it was already defined in the project table.

The interesting thing is that the groupBy('project_id') doesn't work at all, not sure why as its has never returned a grouped item by project_id, even thought it is in the primary timesheet_entries table.

still need a solution to that one!

6th July, 2017

mstarkey left a reply on Property Does Not Exist On This Collection Instance. • 4 months ago

Sadly not the case. I tried a variety of calls and all seem to rely on a function to render the object as a readable array, I added ->first() and got results but only the first item, its a start but I am trying to do the following:

show the total hrs spent on each project for a client between 2 dates.

I am returning some data now using:

ReportsController.php

public function report(Request $request)
    {
        $time = explode(" - ", $request->input('time'));
        $client_id = $request->input('client_id');
        $project_id = $request->input('project_id');
        $start = $this->change_date_format($time[0]);
        $end = $this->change_date_format($time[1]);

        $entries = TimesheetEntry::with('client','project','timesheetTask','timesheet')
            ->where('client_id', $client_id)
            ->whereBetween('timesheet_entries.updated_at', [$start, $end])
            ->get();
        $items = collect($entries)->groupBy('project_id');
        $items->values()->all();

        return view('_modules.admin.reports.report', compact('items','start','end'));

    }
report.blade.php

@foreach($items->flatten() as $item)
       <tr>
              <td>{{ $item->client->name }}</td>
              <td>{{ $item->project->project_name }}</td>
       </tr>
@endforeach

this gives me a list, but I think it may not be an accurate list and doesn't group.

mstarkey started a new conversation Property Does Not Exist On This Collection Instance. • 4 months ago

I keep coming up agains this problem it doesn't make any sense as the data I am requesting has data and is nested in a collection, I solved it with another instance by using find(1) in the query but that was for one result with multiple relationships i.e. user->projects.

The following code returns a json object with the correct data.

ReportsController.php

public function report(Request $request)
    {
        $time = explode(" - ", $request->input('time'));
        $client_id = $request->input('client_id');
        $start = $this->change_date_format($time[0]);
        $end = $this->change_date_format($time[1]);

        $entries = TimesheetEntry::with('client','project','timesheetTask','timesheet')
            ->where('client_id', $client_id)
            ->whereBetween('timesheet_entries.updated_at', [$start, $end])
            ->get();
        $items = collect($entries)->groupBy('project_id');

        return $items;

    }

The thing is, is that when I try to render the view with blade I get the ErrorException (Property [client] does not exist on this collection instance.)

report.blade.php

@foreach($items as $item)
      <tr>
             <td>{{ $item->client->name }}</td>
             <td>{{ $item->project->name }}</td>
      </tr>
@endforeach

I have searched everywhere for a definitive answer but nothing even comes close to explaining it. I have read Adam Wathans book on collections and no mention of this issue.

your help would be so welcome at this point.

many thanks

Mark

26th June, 2017

mstarkey left a reply on Collections: How Do I Group Items And Sum Results • 4 months ago

Hi @cipsas

the results I am looking to return is

client->project->totalHours

I am using the groupBy to bring the multiple timesheet_entries together and then sum the hours.

I have added the ->with('client'), i did forget that one, so thanks for that.

If I use the groupBy method I return (Property [client] does not exist on this collection instance.)

collections confuse me just a bit

mstarkey started a new conversation Collections: How Do I Group Items And Sum Results • 4 months ago

I am trying to gather a collection of results, group them and add the figures together.

I have achieved the groupBy with this code:

$entries = TimesheetEntry::where('client_id', $client_id)
            ->where('project_id', $project_id)
            ->whereBetween('timesheet_entries.updated_at', [$start, $end])
            ->get();

        $items = collect($entries)->groupBy('project_id');

But this will now display on the front end as the 'client' object cannot be found:

@foreach($items as $item)
        <tr>
               <td>{{ $item->client->name }}</td>
               <td>{{ $item->project->number .' - '. $item->project->name }}</td>
               <td>{{ $item->timesheet->user->full_name }}</td>
               <td>{{ $item->mon_hrs }}</td>
        </tr>
@endforeach 

once this is solved I will then need to 'sum' the total hours for the week. I did achieve this by:

$total = $times->sum(function ($entry) {
            return $entry->mon_hrs + $entry->tue_hrs + $entry->wed_hrs + $entry->thu_hrs + $entry->fri_hrs + $entry->sat_hrs + $entry->sun_hrs;
        });

but this just seems messy

have real trouble with this and would really appreciate a guiding hand.

many thanks

Mark

mstarkey left a reply on Raw SQL Vs Eloquent Query • 4 months ago

Found the solution to this one, using hasManyThrough on the User Model:

public function timesheet_entries()
    {
        return $this->hasManyThrough(Timesheet::class, TimesheetEntry::class);
    }

21st June, 2017

mstarkey left a reply on Raw SQL Vs Eloquent Query • 5 months ago

Thanks for replying CJ, my structure only associates the timesheet with the user, so..

user hasMany timsheets and timesheets hasMany timesheetEntries.

I need to be able to access the user from the timesheet entry. I am thinking belongToThrough but I am no so good at the advanced relationships like 'through and polyMorphic'

mstarkey started a new conversation Raw SQL Vs Eloquent Query • 5 months ago

Hi,

I am trying to get my head round using a collection instead of a DB:: query the following code returns results a a json object but is not quite what i need:

$entries = DB::table('timesheet_entries')
            ->join('timesheets', 'timesheet_entries.timesheet_id', '=', 'timesheets.id')
            ->where('client_id', $client_id)
            ->where('project_id', $project_id)
            ->whereBetween('timesheet_entries.updated_at', [$start, $end])
            ->select('timesheet_entries.*', 'timesheets.user_id')
            ->get();

I got part of the way but I am struggling with the JOIN part of the query here is what I have so far:

$entries = TimesheetEntry::where('client_id', $client_id)
            ->where('project_id', $project_id)
            ->whereBetween('timesheet_entries.updated_at', [$start, $end])
            ->get();

Now the reason I am using eloquent over DB for this is that i have no idea how to get blade to display data objects from a DB:: query as whoops tells me it can't.

any help would be greatly appreciated as this will fix 4 potential issues I have found so far

4th July, 2016

mstarkey left a reply on One To Many • 1 year ago

I use one table for categorisation and use the schema

Category
id
name
parent_id

the result will allow you to nest the sub categories and move them if needed as a block, you can also negate the current category as a parent option. Keeps the whole thing clean and lean

8th June, 2016

mstarkey left a reply on Valet Paths Not Working • 1 year ago

Have you tries running valet link inside each site directory this will add a symlink to that directory

or try www.site2.dev and www.site1.dev, it works for me

2nd September, 2015

mstarkey left a reply on Using Bcrypt For Password Hashing • 2 years ago

Thank you all for your solutions, I went with the first model based solution as this fitted best with how I wanted the controller and model used, I also learned something from all the solutions, so once again thanks for your time it so very much appreciated.

mstarkey started a new conversation Using Bcrypt For Password Hashing • 2 years ago

I am trying to create a function to add users to my system using name , email, start_date and password.

I ac save all the data to the database row but cannot for the life of me hash the password using bcrypt, it should be relatively easy but i am missing something.

public function store(UserRequest $request, User $user) { $user->create($request->all()); return redirect('admin/users'); }

As you can see I have a create all store function but need to add the password hashing to it. any pointers please?

17th October, 2014

mstarkey left a reply on Show Method Bumps The Create Method • 3 years ago

How infuriating! it was staring me in the face! Thanks @aliqsyed top reply you saved me a brain haemorrhage :)

16th October, 2014

mstarkey started a new conversation Show Method Bumps The Create Method • 3 years ago

This is starting to bend my brain, when i comment out the show method the create method works, when uncomment the show method the error Trying to get property of non-object (View: /home/vagrant/Sites/OfficeBoy/resources/views/management/users/show.blade.php) appears

am i missing something as all the other method work a treat

annotations are not the issue as route:list returns all methods correctly with names.

UsersController.php ''' /** * * @return View * @Get("users/{id}", as="management_user_path") */ public function show($id) { $user = $this->user->find($id);

    return view('management.users.show', compact('user'));
}

/**
 * @Param User $user
 * @return View
 * @Get("users/create", as="management_create_user_path")
 */
public function create()
{
    return view('management.users.create');
}

'''

Your help dear Artisans would be great :)

7th October, 2014

mstarkey left a reply on 'Illuminate\Foundation\Support\Providers\FilterServiceProvider' Not Found • 3 years ago

Yeah, but isn't it exciting to see this stuff unfold and it really does make you read the doc more closely, well at least it does for me anyway :)

mstarkey left a reply on 'Illuminate\Foundation\Support\Providers\FilterServiceProvider' Not Found • 3 years ago

There seems to be a few update that will break the latest update,you need to do the following to get rid of some of the errors;

remove 'App\Providers\FilterServiceProvider' from the app.php file remove 'use Illuminate\Routing\Controller;' from your controllers remove 'extends Controller' from your controllers

I know its a bit mad crazy but Taylor seems to had mad the 'controller class' autoload

I am loving this bleeding edge stuff, it's why I became a developer, and Laravel is getting better every day not just very release.

10th September, 2014

mstarkey left a reply on Launch Of Laravel 4.3 • 3 years ago

Thanks for all your advise @pobble, @Rahul and @vengiss, I think because I am just starting to put code together, it might be a good time to start using 4.3, from my initial tests it works very well with what I am trying to do. The videos help me understand the new features and I guess by the time I get deep into the heavy lifting The 4.3 release will be ready. With regards to packages, I have decided at this point to work on the parts that do not rely on too many 3rd party packages and will stick with the laravel standards, swapping out if need be, I plan to use interface throughout as I am hoping the app will have a use for a lot of people.

mstarkey left a reply on Launch Of Laravel 4.3 • 3 years ago

With the impending launch of Laravel 4.3, my question is this, should I start using 4.3 on a new side project that will release first quarter of 2015 of start in 4.2 and upgrade?

I am at 2 minds to whether this is a good plan or just jumping the gun. Thoughts?

Edit Your Profile
Update

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