ctyler

ctyler

Member Since 1 Year Ago

Experience Points
14,280
Total
Experience

720 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
136
Lessons
Completed
Best Reply Awards
0
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.

Level 3
14,280 XP
Oct
25
3 weeks ago
Activity icon

Awarded Best Reply on Can You Use An Aggregate On A Nested Eager Load?

I just figured it out. This works perfectly.

$courses = Course::with('attendance.attendancesessions')
            ->when($cat, function ($query, $cat){
                return $query->where('course_cat_id', $cat);
            })
            ->when($from, function ($query, $from) {
                return $query->where('start_date', '>=', $from); //2020-02-01
            })
            ->when($to, function ($query, $to) {
                return $query->where('start_date', '<=', $to); //2020-02-29
            })
            ->sortable(['start_date' => 'desc'])
            ->paginate(25);

Then output in view:

@foreach($courses as $course)
            <tr>
                <td class="text-center">{{  $course->id }}</td>
                <td class="text-left"><a href="#">{{  $course->name }}</a> </td>
                <td class="text-center">{{ \Carbon\Carbon::parse($course->start_date)->format('m/d/Y') }}</td>
                <td class="text-center">
                    {{ (empty($course->attendance->attendancesessions->last()->session_date) ? $course->end_date : \Carbon\Carbon::parse($course->attendance->attendancesessions->last()->session_date)->format('m/d/Y')) }}

                </td>
    </tr>
@endforeach
Activity icon

Replied to Can You Use An Aggregate On A Nested Eager Load?

I just figured it out. This works perfectly.

$courses = Course::with('attendance.attendancesessions')
            ->when($cat, function ($query, $cat){
                return $query->where('course_cat_id', $cat);
            })
            ->when($from, function ($query, $from) {
                return $query->where('start_date', '>=', $from); //2020-02-01
            })
            ->when($to, function ($query, $to) {
                return $query->where('start_date', '<=', $to); //2020-02-29
            })
            ->sortable(['start_date' => 'desc'])
            ->paginate(25);

Then output in view:

@foreach($courses as $course)
            <tr>
                <td class="text-center">{{  $course->id }}</td>
                <td class="text-left"><a href="#">{{  $course->name }}</a> </td>
                <td class="text-center">{{ \Carbon\Carbon::parse($course->start_date)->format('m/d/Y') }}</td>
                <td class="text-center">
                    {{ (empty($course->attendance->attendancesessions->last()->session_date) ? $course->end_date : \Carbon\Carbon::parse($course->attendance->attendancesessions->last()->session_date)->format('m/d/Y')) }}

                </td>
    </tr>
@endforeach
Activity icon

Started a new Conversation Can You Use An Aggregate On A Nested Eager Load?

Hello all, So i have a database that contains courses. Each course has one attendance. Each attendance can have multiple Sessions. The course table has the start_date column. The end date for the course is the last session. I am currently using a sub query for this:

$end_date = DB::table('attendances')
            ->select('attendances.course_id', DB::raw('MAX(attendancesessions.session_date) as end_date'))
            ->leftjoin('attendancesessions', 'attendances.id', '=', 'attendancesessions.attendance_id')
            ->groupBy('attendances.course_id');

$courses = $course
            ->JoinSub($end_date, 'end_date', function ($join) {
                $join->on('id', '=', 'end_date.course_id');
            })
            ->when($cat, function ($query, $cat){
                return $query->where('course_cat_id', $cat);
            })
            ->when($from, function ($query, $from) {
                return $query->where('start_date', '>=', $from); //2020-02-01
            })
            ->when($to, function ($query, $to) {
                return $query->where('start_date', '<=', $to); //2020-02-29
            })
            ->sortable(['start_date' => 'desc'])
            ->paginate(25);

This works okay but I was wondering if I could use an Aggregate on a Nested Eager Load some how.

$cousres = Course::with('attendance.attendancesessions')
        ->get();
        foreach($cousres as $course) {
            dd($course->attendance->attendancesessions->last());
        }

This works but I need to use last() with a column session_date. When I try to pass session_date via:

$course->attendance->attendancesessions->last('session_date')

I get an error: Argument 1 passed to Illuminate\Support\Collection::last() must be callable or null, string given, called in /var/www/html/dev-cls-training-com/app/Http/Controllers/Admin/CourseController.php on line 71

Oct
07
1 month ago
Activity icon

Replied to Stored Procedure Always Return An Empty Array

OMG. Turns out I did not convert my Variables into the parameters when changing to stored procedure. How embarrassing. Sorry.

Activity icon

Started a new Conversation Stored Procedure Always Return An Empty Array

Good After noon all. I am having an issue running a stored procedure in a Controller: Laravel 5.8 Mariadb: 10.4.8

Here is the stored procedure:

DELIMITER $$
CREATE DEFINER=`dbuser`@`10.6.12.18` PROCEDURE `GetStudentsToGrade`(
    IN course_ID INT,
    IN assignmentID INT
)
BEGIN
    SELECT c.id as courseID, c.name, count(sess.id) as TotalSessions, y.userID, y.firstname, y.lastname, y.NoAttended, y.SessionID, y.updated_at, z.grade, z.updated_at
FROM courses c
JOIN attendances a on c.id = a.course_id
left join attendancesessions sess on a.id = sess.attendance_id
LEFT JOIN
(
                SELECT c.id as courseID, u.id as userID, u.firstname, u.lastname, sess.id as SessionID, count(al.status) as NoAttended, al.updated_at
                FROM attendancelogs as al
                join attendancesessions sess on al.attendancesession_id = sess.id
                join attendances a on sess.attendance_id = a.id
                join courses c on a.course_id = c.id
                join users u on al.user_id = u.id
                WHERE c.id = @courseID
                AND al.status = 1
    GROUP BY userID, courseID
) as y on c.id = y.courseID
LEFT JOIN
(
                SELECT users.id, users.firstname, users.lastname, assign_grades.grade, assign_grades.updated_at, assign_grades.assignment_id
                FROM assign_grades
                LEFT JOIN users on assign_grades.user_id = users.id
                JOIN assignments on assign_grades.assignment_id = assignments.id
                WHERE assignments.id = @assignmentID
) as z on y.userID = z.id
WHERE courseID = @courseID
GROUP BY y.userID, c.id
HAVING  TotalSessions = y.NoAttended;
END$$
DELIMITER ;

If I run this in MySQL Workbench I get the result I expect.

CALL GetStudentsToGrade(5, 97);

Now in the controller:

$studentsToGrade = DB::select(DB::raw("call GetStudentsToGrade('$course->id', '$assignment->id')"));

dd($studentsToGrade, $course->id, $assignment->id);

The dump show:

[]

5

97

I also tried:

$studentsToGrade = DB::select(DB::raw("call GetStudentsToGrade(5, 97)"));

With the same results. I cannot seem to figure out why this is not working,

Any help would be greatly appreciated.

Jun
26
4 months ago
Activity icon

Replied to Are View Composers Only For Static Queries?

@DARKROAST - Brilliant! That's exactly what I needed.

 $params = Route::current()->originalParameters();
        // Dependencies automatically resolved by service container...
        //$this->users = $users;
        $studentsEnrolled = Enrollment::totalStudentsEnrolled($params['course']);
        $this->studentsEnrolled = $studentsEnrolled;

One thing for anyone looking this up after the fact. If you create a Service Provider for your view composers, be sure to execute: php artisan config:clear and php artisan clear-compiled Laravel did not recognize my service provider until after. Hopefully that will save someone some time!

Thank you.

Activity icon

Started a new Conversation Are View Composers Only For Static Queries?

I am rather new to View Composers so I am a little confused.

I am working on a training site. I have a view for classes that shows the number of students allowed, students enrolled and the number of sets remaining. I think that a View composer would be great for this but the problem is, in my limited understanding of composers, I cannot seem to figure out how to pass a variable to the view composer. Is this possible.

So for instance if the url is /coursecat/1/course/1 Can I pass the Course ID into the View Composer?

Thank you!

Jun
13
5 months ago
Activity icon

Replied to Issue Adding Days In A For Loop

@JOHNBRAUN - No problem! I appreciate the time and effort!

Activity icon

Replied to Issue Adding Days In A For Loop

@johnbraun - Thanks, your the best. Heading over there now!

Activity icon

Replied to Issue Adding Days In A For Loop

@snapey @johnbraun @mgsmus I have a question concerning this code. So, this is all happening inside the controller. Should i break this up into methods. So for instance, make the outer and inner for loops their own methods. And if so, would they go into their respective models or would it be better someplace else. I appreciate your thoughts on it.

Activity icon

Replied to Issue Adding Days In A For Loop

So....I made some changes and the initial changes seem to indicate it is working

$courseDate = new Carbon($validated['start_date']);
for($i = 0; $i < $validated['no_classes'];$i++) {
                $course = Course::create([
                    'course_cat_id' => $coursecat->id,
                    'name' => $coursecat->name . ' : ' . $courseDate->format('Y-m-d'),
                    'start_date' => $courseDate->format('Y-m-d'),
                    'start_time' => $validated['start_time'],
                    'end_time' => $validated['end_time'],
                    'summary' => $validated['description'],
                ]);
                $sessionDate = new Carbon($courseDate); // Make a new carbon object and copy it into session date before adding days. This is then used in second iteration. and can be modified independantly of $courseDate
                $courseDate->add($validated['interval'], 'day');
                $no_courses++;
                $attendance = Attendance::create([
                    'course_id' => $course->id,
                ]);
                for($a = 0; $a < $validated['attendance_sessions'];$a++) {
                    Attendancesession::create([
                        'attendances_id'    => $attendance->id,
                        'session_starttime' => $validated['start_time'],
                        'session_endtime' => $validated['end_time'],
                        'session_date' => $sessionDate,
                    ]);
                    $sessionDate->add($validated['session_interval'], 'day');
                }

Thanks everyone for your help. @snapey @johnbraun @mgsmus

Activity icon

Replied to Issue Adding Days In A For Loop

@SNAPEY - @snapey - I did not perceive that. Thank you, that helps.

Jun
12
5 months ago
Activity icon

Started a new Conversation Issue Adding Days In A For Loop

Hello all, I am working on a training application. Trainers will need to take attendance for a course. So when generating course(s), admins can select: Start date, number of courses, Interval between courses, Number of session, Interval between sessions.

So each course will have an attendance object. Each attendance object will have one or more sessions. The problem I am having is the sessions and the dates.

$validated = $request->validated()
$no_courses = 0;
$courseDate = new Carbon($validated['start_date']); //Comes from the form
//The course, for loop,  works great
for($i = 0; $i < $validated['no_classes'];$i++) {
                $course = Course::create([
                    'course_cat_id' => $coursecat->id,
                    'name' => $coursecat->name . ' : ' . $courseDate->format('Y-m-d'),
                    'start_date' => $courseDate->format('Y-m-d'),
                    'start_time' => $validated['start_time'],
                    'end_time' => $validated['end_time'],
                    'summary' => $validated['description'],
                ]);
                $courseDate->add($validated['interval'], 'day');
                $no_courses++;
                $attendance = Attendance::create([ //One attendance object per course. this works
                    'course_id' => $course->id,
                ]);
//So the number of session_date is the problem. Course can span multiple days and attendance will need to be taken every day (session).
                for($a = 0; $a < $validated['attendance_sessions'];$a++) {
                    $sesssionDate = $courseDate;
                   Attendancesession::create([
                        'attendances_id'    => $attendance->id,
                        'session_starttime' => $validated['start_time'],
                        'session_endtime' => $validated['end_time'],
                        'session_date' => $sesssionDate,
                    ]);
                    $sesssionDate = $sesssionDate->addDays($validated['session_interval']); //This is not working in this for loop. The number of 'session_interval' in days should be added each iteration. 
                }
    }

So once this runs the Courses are created with the correct number of days between each course. The sessions, on the other hand, all have the same date which is the first course date when they are supposed to start on the first course created date and the session_interval between the rest of the sessions.

I hope I explained it clearly.

Any assistance would be appreciated.

Jun
07
5 months ago
Activity icon

Replied to Nested Resource Controllers

@sirhxalot It was the camel case of the variable. Found it completely by accident. Changed it from $courseCat to $coursecat and boom! It worked. I cannot believe how much time I wasted on this, not to mention yours and @fraserk

My apologies for a silly mistake. So, my question is, does the variable always have to be lower case or does it have to follow the case in the route - {coursecat}. My guess is that latter.

Jun
06
5 months ago
Activity icon

Replied to Nested Resource Controllers

I will try that first thing in the AM.

Activity icon

Replied to Nested Resource Controllers

@sirhxalot - The model? Yes. I do have an ID in my migration:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCourseCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('course_categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('course_categories');
    }
}
Activity icon

Replied to Nested Resource Controllers

@sirhxalot , @fraserk That is exactly what I have:

class CourseCat extends Model
{
    use Sortable;
    public $sortable = [
        'id',
        'name',
    ];

   // protected $dates = ['start_date', 'end_date'];


    protected $fillable = [
        'name', 'description', 'start_date', 'end_date', 'assignments_no', 'seats', 'wait_lists', 'certificates', 'attendance_sessions'
    ];
    protected $table = 'course_categories';

    public function courses()
    {
        return $this->hasMany('App\Courses');
    }
}
Activity icon

Replied to Nested Resource Controllers

@fraserk There is no pivot table. That is the name of the course category table. However, could the naming convention be an issue?

Activity icon

Replied to Nested Resource Controllers

@sirhxalot, I believe I did when I set it up. I believe that simply puts the type hinting as a parameter on your actions

Activity icon

Replied to Nested Resource Controllers

Hi @sirhxalot The model says false for exists. However, I added the id to the dd()

{{ dd($courseCat->id) }}

It is returning null.

Activity icon

Started a new Conversation Nested Resource Controllers

I am having difficulty with nested resource controllers. If I have a resource controller:

Route::resource('coursecat.course', 'CourseController');

That give me these routese (via php artisan route:list) I get the following routes:

admin                                                    |                          | Closure                                                                     | web                                 |
|        | POST      | admin/coursecat                                          | coursecat.store          | App\Http\Controllers\Admin\[email protected]                        | web                                 |
|        | GET|HEAD  | admin/coursecat                                          | coursecat.index          | App\Http\Controllers\Admin\[email protected]                        | web                                 |
|        | GET|HEAD  | admin/coursecat/create                                   | coursecat.create         | App\Http\Controllers\Admin\[email protected]                       | web                                 |
|        | PUT|PATCH | admin/coursecat/{coursecat}                              | coursecat.update         | App\Http\Controllers\Admin\[email protected]                       | web                                 |
|        | GET|HEAD  | admin/coursecat/{coursecat}                              | coursecat.show           | App\Http\Controllers\Admin\[email protected]                         | web                                 |
|        | DELETE    | admin/coursecat/{coursecat}                              | coursecat.destroy        | App\Http\Controllers\Admin\[email protected]                      | web                                 |
|        | POST      | admin/coursecat/{coursecat}/course                       | coursecat.course.store   | App\Http\Controllers\Admin\[email protected]                           | web                                 |
|        | GET|HEAD  | admin/coursecat/{coursecat}/course                       | coursecat.course.index   | App\Http\Controllers\Admin\[email protected]                           | web                                 |
|        | GET|HEAD  | admin/coursecat/{coursecat}/course/create                | coursecat.course.create  | App\Http\Controllers\Admin\[email protected]                          | web                                 |
|        | DELETE    | admin/coursecat/{coursecat}/course/{course}              | coursecat.course.destroy | App\Http\Controllers\Admin\[email protected]                         | web                                 |
|        | PUT|PATCH | admin/coursecat/{coursecat}/course/{course}              | coursecat.course.update  | App\Http\Controllers\Admin\[email protected]                          | web                                 |
|        | GET|HEAD  | admin/coursecat/{coursecat}/course/{course}              | coursecat.course.show    | App\Http\Controllers\Admin\[email protected]                            | web                                 |
|        | GET|HEAD  | admin/coursecat/{coursecat}/course/{course}/edit         | coursecat.course.edit    | App\Http\Controllers\Admin\[email protected]                            | web                                 |
|        | GET|HEAD  | admin/coursecat/{coursecat}/edit                         | coursecat.edit           | App\Http\Controllers\Admin\[email protected]

In my CourseController, for my index() action, I have:

public function index(CourseCat $courseCat)
    {
        return view('admin.course.index', compact('courseCat'));
    }

In my admin.course.index view I have

{{ dd($courseCat) }}

So, if I visit http://10.0.0.2/admin/coursecat/10/course I would expect to see the output of CourseCat object with the ID of 10. However, it is returning:

CourseCat {#458 ▼
  +sortable: array:2 [▶]
  #fillable: array:9 [▶]
  #table: "course_categories"
  #connection: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #attributes: []
  #original: []
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}

I am not sure why that is not working. Does route model binding not work with nested controllers. Is there something I need to do special for nested controllers.

Any help would be appreciated.

May
15
6 months ago
Activity icon

Replied to Telescope Not Logging Registered Event

I was just doing some more research on this. Apparently internal events are ignored - per the documentation:

Event Watcher The event watcher records the payload, listeners, and broadcast data for any events dispatched by your application. The Laravel framework's internal events are ignored by the Event watcher.

Activity icon

Replied to How To Create Custom Email Verification Template | Laravel 5.7

@martinbean

It looks like you can access the users details because the event is called from the user in vendor/laravel/framework/src/Illuminate/Auth/Listeners/SendEmailVerificationNotification.php

class SendEmailVerificationNotification
{
    /**
     * Handle the event.
     *
     * @param  \Illuminate\Auth\Events\Registered  $event
     * @return void
     */
    public function handle(Registered $event)
    {
        if ($event->user instanceof MustVerifyEmail && ! $event->user->hasVerifiedEmail()) {
            $event->user->sendEmailVerificationNotification();
        }
    }
}

I am assuming that means you can personalize the email? How would you access the user detail from the emails.verify markdown?

P.S. I just asked this question before I seen this post, sorry.

Activity icon

Started a new Conversation Telescope Not Logging Registered Event

So I am using Telescope for testing and troubleshooting.

When a person registers they are to select an employer form a drop down. The employer is to get an email so they can log in and verify that that person was in-fact hired by them. I need to be able to fire an email off to the employer notifying them they have a new employee register and they need to approve it.

So I go into the EventServiceProvider.php and see:


protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

I see the event Registers and its listener, however there is no Event or Listener folders in app/. That is not surprising, however, what is surprising is telescope is not picking up the Event Registered when the email verification is mailed. Telescope picks up that but not the event itself and therefore not the listener either.

I heard of logging being effected if the APP_ENV is not local. Mine is local.

Any help in this area would be appreciated.

Activity icon

Started a new Conversation How To Modify/Personalize Email Verification Email

Good Morning, I am having an issue with customizing the email verification email. I have seen a few work-arounds that seem clumsy to me and uncharacteristic of what I have seen so far from laravel. I would like to use a custom markdown that I can pass the user to so I can personalize the email. Is there a way to do this and if so, what is the best way to do this?

Thanks in advance Casey