Talinon

Talinon

Member Since 4 Years Ago

Toronto

Experience Points
214,460
Total
Experience

540 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
1031
Lessons
Completed
Best Reply Awards
176
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 43
214,460 XP
May
25
5 days ago
Activity icon

Awarded Best Reply on Call To Undefined Function GetUser() After Deploy On Heroku Serve

@spiral You have the helper defined under autoload-dev, so of course it won't work on production.

Activity icon

Awarded Best Reply on Seeing Puzzling And Inconsistent Results With Unit Test

@connecteev I think your other methods worked because you were creating a model then asserting against it. With the update method, you already had an instance of a model, then applied an update to a related piece of data, then asserted against the original instance without the changes. Using refresh() will reload the model, along with it's relationships (which would include the changes you made via the PUT request)

It's not necessarily any bad practice on your behalf, it's just something to be aware of. You will require to refresh your model from time to time with unit testing to make a test pass. It's one of the reasons why the refresh() method was included within the framework. Alternatively, if you don't want to refresh the model, you could always assert against the database.

May
24
6 days ago
Activity icon

Replied to Seeing Puzzling And Inconsistent Results With Unit Test

@connecteev I think your other methods worked because you were creating a model then asserting against it. With the update method, you already had an instance of a model, then applied an update to a related piece of data, then asserted against the original instance without the changes. Using refresh() will reload the model, along with it's relationships (which would include the changes you made via the PUT request)

It's not necessarily any bad practice on your behalf, it's just something to be aware of. You will require to refresh your model from time to time with unit testing to make a test pass. It's one of the reasons why the refresh() method was included within the framework. Alternatively, if you don't want to refresh the model, you could always assert against the database.

Activity icon

Replied to Laravel Prefix Route Not Found

@adeguntoro check the output of php artisan route:list for clues

Activity icon

Replied to Controller Input Validation Help

@mitchmoon:

If your select element is holding string values: required|string|min:1|max:30

Activity icon

Replied to Seeing Puzzling And Inconsistent Results With Unit Test

@connecteev Oh I see, I was just a bit confused by the way you had the code snippet.

Hmm.. have you tried refreshing the model?

$isUserSubscribed = $user->refresh()->subscribed(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'));
Activity icon

Replied to Seeing Puzzling And Inconsistent Results With Unit Test

@connecteev

Shouldn't your endpoint being using $loggedInUser and not $user?

 $loggedinUser = auth()->user();
        $loggedinUser->newSubscription(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'), $stripePlanId)->create($paymentMethodId);

// below you have $user, not $loggedInUser
$isUserSubscribed = $user->subscribed(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'));

Also, FYI, it is best practice to use config() over env() within your code. That way, you can cache your configuration - otherwise, everytime your application calls env() it's going to read to the disk, which is very slow.

Activity icon

Replied to Call To Undefined Function GetUser() After Deploy On Heroku Serve

@spiral You have the helper defined under autoload-dev, so of course it won't work on production.

Activity icon

Replied to Laravel UpdateOrcreate Missing Value

@artyak Looks to me like you have them reversed.. check out the end of my edited response above

Activity icon

Replied to Laravel UpdateOrcreate Missing Value

@artyak I just skimmed over your code, but the thing that jumped out at me is that you're not passing both parameters to updateOrCreate() in two places.

The method signature takes 2 parameters, the first being an array for what fields and values to match against, the second parameter being another array for what fields to update.

 $tournament = Tournament::updateOrCreate([
        'tournament_id' => $tournament_id,
        'league_name'   => $full_name
    ], [
                // missing this data
    ]);

Same here:

Tournament_matches::updateOrCreate([
            'name'       => $match->name,
            'started_at' => Carbon::parse("$match->begin_at,")->setTimezone('Europe/Berlin'),
            'ended_at'   => $match->end_at,
            'winner_id'  => $team->id ?? null,
            'status'     => $status,
            'match_id'   => $match->id,
            'live'       => $match->live_url,
        ]),
	[
			// missing this data
	]);


You probably want something like this:

Tournament_matches::updateOrCreate([
            'match_id'   => $match->id,
	], [
            'name'       => $match->name,
            'started_at' => Carbon::parse("$match->begin_at,")->setTimezone('Europe/Berlin'),
            'ended_at'   => $match->end_at,
            'winner_id'  => $team->id ?? null,
            'status'     => $status,
            'live'       => $match->live_url,
        ]);

May
21
1 week ago
Activity icon

Replied to Import / Export Using Maatwebsite\Excel

@ved21212 Version 3 has taken a much more OOP approach. As a result, it is not backwards compatible with 2.x and you are getting that error because a lot of 2.x methods are deprecated.

You can read the upgrade guide here:

https://docs.laravel-excel.com/3.0/getting-started/upgrade.html

May
19
1 week ago
Activity icon

Awarded Best Reply on Prevent Cascading Parameteres (OOP Solution Needed)

@randy_johnson I don't think it has anything to do with your switch statement. Sounds like you're missing a return statement before your view method calls.

switch ($something)
	case 1:
		$this->view1();  // will result in view not being shown
switch ($something)
	case 1:
		return $this->view2();  // returns the result from the method
Activity icon

Replied to Undefined Variable When Passing Data To A Function Or Method

@randy_johnson I explained to you why you were experiencing data not being returned within your controller from yesterday's thread. Bloating controller methods is not a solution.

@underscoresdev Are you sure you are calling that function? It looks like you're calling a helper function -- are you in the correct namespace? Maybe you've added a method to your controller but you're not using $this which is calling a helper function instead of the class method?

$this->create_form_config($validInput) ??

Try something like this to make sure you're actually calling the function:

function create_form_config( array $input ) {
	dd('called');
	...
}

May
18
1 week ago
Activity icon

Replied to Prevent Cascading Parameteres (OOP Solution Needed)

@randy_johnson I don't think it has anything to do with your switch statement. Sounds like you're missing a return statement before your view method calls.

switch ($something)
	case 1:
		$this->view1();  // will result in view not being shown
switch ($something)
	case 1:
		return $this->view2();  // returns the result from the method
Activity icon

Replied to Prevent Cascading Parameteres (OOP Solution Needed)

@randy_johnson

The first thing I'd likely do is move the call to your utility class into your controller. Let your controller decide what path to take and then pass the results into your view.

Next, instead of having two methods on your utility class, perhaps you could go about it in a more OOP way, by extending the class. Then you'd invoke one of the concrete classes to handle the address update.

Another thing you could consider is just using the request() helper instead of passing the Request object around, which is a clean, viable way of handling it, especially if you're not manipulating anything within it.

May
14
2 weeks ago
Activity icon

Replied to Job That Is Not Scheduled Keeps Running Every Minute

@KimG I'd check all the processes running on the server. Perhaps someone accidentally forked an instance of the queue worker from the terminal and it's been living for weeks.

Something like this should identify all queue worker processes: ps -aux | grep "queue"

Apr
16
1 month ago
Activity icon

Replied to How To Get Middleware To Fire?

@alecweekes I would suggest changing the way you're writing your tests. You are treating a feature test like a unit test, which is giving you undesirable results.

Instead, harness the Laravel testing API. Just a simple example:

public function a_guest_cannot_do_whatever()
{

	// just to make sure you don't have a signed in user in the test's setUp()
	auth()->lougout();   

	$response = $this->get('/route');

	$response->assertRedirect();
// or assertStatus(404) or whatever is appropriate for your app

}


public function an_authenticated_user_can_do_whatever()
{

	$user = factory(User::class)->create();

        $response = $this->actingAs($user)
			->get('/route');

	$response->assertStatus(200);

}

If you want to bypass middleware, you can always call this method:

 public function test_example()
 {
        $this->withoutMiddleware();

	// test code
}
Apr
14
1 month ago
Activity icon

Started a new Conversation UpdateOrCreate() Case Sensitivity

Context: Synchronizing data with Microsoft's Graph API

Problem: Items have immutable ids that are case sensitive. There are many occurrences where unique items have the exact same Id, except for a single character having a different casing.

i.e.: (notice the 4th last character)

Item #1: EWg0AQbLDgfAFWEaaZsFuzmolNQAAAADDIQAA

Item #2: EWg0AQbLDgfAFWEaaZsFuzmolNQAAAADDiQAA

When using updateOrCreate() the underlying where() method generates a query against MySQL that returns a case insensitive result set.

Normally, I can get around this using whereRaw() and parameter binding, such as:

$id = 'casE seNsitive id';
Model::whereRaw("BINARY `graph_immutable_id`=?", [$id])->first();

However, for convenience, I would like to apply the same condition to updateOrCreate().

If I chain the above whereRaw() condition before updateOrCreate() it seems like it solves the issue:

Model::whereRaw("BINARY `graph_immutable_id`=?", [$id])
        ->updateOrCreate([], [$arrayOfProperties]);

From what I gather by skimming over the code base, this works because Builder will just add the extra condition onto the query, and I end up with the unique model.

Does anyone see any issue with this approach? Is there another way of going about this that I haven't thought of? (besides performing the raw query and then writing the code to either update or create manually)

Thanks

Apr
04
1 month ago
Activity icon

Awarded Best Reply on Testing Laravel HTTPNOTFOUND Exception On Second Pass

Do you have multiple route files?

Check out this thread, sounds like it could very well be your issue:

https://stackoverflow.com/questions/23418150/unable-to-run-multiple-controller-tests-in-laravel

Apr
01
1 month ago
Activity icon

Awarded Best Reply on How To Not Loop The Same Data In Foreach ?

@fareedr

Assuming you're using a collection, just use the unique() method

https://laravel.com/docs/6.x/collections#method-unique

Activity icon

Replied to How To Not Loop The Same Data In Foreach ?

@fareedr

Assuming you're using a collection, just use the unique() method

https://laravel.com/docs/6.x/collections#method-unique

Mar
27
2 months ago
Activity icon

Awarded Best Reply on General Error: 1 No Such Table: Main.id (SQL: Insert Into "sessions"...)

@tills98 Your problem is within your migration:

$table->foreign('journey_id')->references('journeys')->on('id');

Should be:

$table->foreign('journey_id')->references('id')->on('journeys');
Mar
26
2 months ago
Activity icon

Replied to General Error: 1 No Such Table: Main.id (SQL: Insert Into "sessions"...)

@tills98 Your problem is within your migration:

$table->foreign('journey_id')->references('journeys')->on('id');

Should be:

$table->foreign('journey_id')->references('id')->on('journeys');
Mar
10
2 months ago
Activity icon

Awarded Best Reply on PHPUnit Segmentation Fault On AWS Elastic Beanstalk Deployment (exit Status 139)

@fylzero I'd start off with runing phpunit with --debug to isolate the test method that is causing it, and then review from there.

Activity icon

Replied to The GET Method Is Not Supported For This Route. Supported Methods: POST

@henryoladj Can you not connect and login to the server via ssh?

Activity icon

Replied to PHPUnit Segmentation Fault On AWS Elastic Beanstalk Deployment (exit Status 139)

@fylzero I'd start off with runing phpunit with --debug to isolate the test method that is causing it, and then review from there.

Activity icon

Replied to The GET Method Is Not Supported For This Route. Supported Methods: POST

@henryoladj Perhaps you have your routes cached? Try clearing it: php artisan route:clear

Mar
07
2 months ago
Activity icon

Replied to WhereBetween Gives Null In Laravel Even When Data Exist !

@princeoo7

Have you tried removing the other where clauses to rule out any interference?

Document::select(['id', 'title', 'type', 'valid_to', 'notification_status', 'user_id', 'status_id'])
            ->with(['owner'])
//            ->whereNotificationStatus(Status::On)
//            ->whereStatusId(Status::Active)
            ->whereBetween('valid_to', [$from, $to])
            ->get();
Feb
27
3 months ago
Activity icon

Awarded Best Reply on Embedding PDF Wishin A PDF Using Laravel-snappy

@browntown Yeah, you might have to resort to another solution, or execute another process that does the merging before serving the file.

You might want to research this, too:

https://www.itsolutionstuff.com/post/laravel-merge-multiple-pdf-files-exampleexample.html

Feb
26
3 months ago
Activity icon

Awarded Best Reply on Why Horizon Save Failed Jobs To Redis?

@kingshark Running php artisan queue:retry all would only push failed jobs within the mysql database back on the queue, so that is expected behaviour.

When you retry a failed job within Horizon, a new job is created. If the new job fails, another new entry should be added to your mysql failed jobs database, but Horizon doesn't delete the original failed job. Now, if you go and push failed jobs back onto the queue from your mysql database using artisan, and they succeed, they'll be removed from the mysql database but not Horizon/Redis (at least I'm pretty sure that is how it works)

So maybe it's just a matter of confusion resulting from pushing jobs with artisan, yet still seeing failed jobs within horizon?

Activity icon

Replied to Why Horizon Save Failed Jobs To Redis?

@kingshark Running php artisan queue:retry all would only push failed jobs within the mysql database back on the queue, so that is expected behaviour.

When you retry a failed job within Horizon, a new job is created. If the new job fails, another new entry should be added to your mysql failed jobs database, but Horizon doesn't delete the original failed job. Now, if you go and push failed jobs back onto the queue from your mysql database using artisan, and they succeed, they'll be removed from the mysql database but not Horizon/Redis (at least I'm pretty sure that is how it works)

So maybe it's just a matter of confusion resulting from pushing jobs with artisan, yet still seeing failed jobs within horizon?

Activity icon

Replied to How To Display Exception Error Msg ?

You're welcome.

Feb
25
3 months ago
Activity icon

Replied to Why Horizon Save Failed Jobs To Redis?

@kingshark It is normal for horizon to store failed job keys, as it uses them to populate the dashboards. You can find their settings for how long Horizon keeps failed data in the config/horizon.php file (if you have it published)

It seems like the main problem is they're not being stored to your mysql table.

I'm not sure why they wouldn't be storing in the database. Are you certain you're checking the right database? (this happens more often than you'd think)

Activity icon

Replied to It Is Necessary To Initialize The Public,protected Variable Inside The Constructor?

@benitto_raj No, it's not necessary, they would default to public. It's a good habit to get into the practice of doing though. It's much easier to look at the top of a class and see all its explicitly defined properties rather than searching thru all the methods.

Usually, you want to avoid using public properties whenever possible. Having public properties means they can be mutated from anywhere in your app (outside the class) and that is generally considered a bad thing.

Activity icon

Replied to Why Horizon Save Failed Jobs To Redis?

@kingshark Do you actually have a period at the end of your environment value, or is that just a typo?

Make sure you don't have your configuration cached.

Run php artisan config:clear

Activity icon

Replied to How To Display Exception Error Msg ?

@somenet77

You are right - you are catching the error. Once you catch the error, you are returning a JsonResponse to your controller:

return response()->json([
                'message' => sprintf('No query result is found with id %d', $id),
                'code' => $e->getCode()
            ]);

Your controller then passes it to CategoryResource where it harfs on your JsonResponse because it's not a model it's expecting.

There are lots of ways to go about correcting this. One quick way would be to check what the repository returns and handle it conditionally within your controller:

 public function show($id)
    {
        $category = $this->category->show($id);

    if ($category instanceof \Illuminate\Http\JsonResponse)
        return $category;  // returns your custom response


    // otherwise pass it on to the JsonResource
        return (new CategoryResource($category))
            ->response()
            ->setStatusCode(Response::HTTP_OK);
    }

My suggestion would be not to return a JsonResponse from your repository. Either return a model or null. Let your controller decide what response to provide.

Activity icon

Awarded Best Reply on Url Validation Including Prefill Http(s)//

@mbo I don't see an issue with just having a select element that forces them to select either http or https. It's easy enough to do string manipulation in the backend to prefix the url with the selection.

Activity icon

Replied to How To Display Exception Error Msg ?

@somenet77 It looks like you need to examine what the find() method on the CategoryContract class is returning. It appears when it does not find an existing resource, it is returning a JsonResponse which does not have a getMedia() method.

public function show($id)
    {
        return $this->categoryContract->find($id);   // <-- is returning JsonResponse when not found
    }

If you're using Eloquent within your CategoryContract, you can catch the ModelNotFoundException within exceptions/handler.php and return a custom json response.

Activity icon

Replied to Url Validation Including Prefill Http(s)//

@mbo I don't see an issue with just having a select element that forces them to select either http or https. It's easy enough to do string manipulation in the backend to prefix the url with the selection.

Feb
24
3 months ago
Activity icon

Replied to How To Seed The Prod Database ?

@mostafalaravel You can use Seeders and execute them via Artisan commands, but you will need to specify the --force flag to run in production (which is a good thing, its a safety mechanism)

or you can use database dumps and import them.. I've used this approach many times.

Activity icon

Replied to The Results Of A Failed Request

@lavina Not sure why you are trying to reinvent the wheel when Laravel comes with user registration out of the box.

But anyway... that is expected behavour for form validation; the Request object protects your controller logic. When the user gets redirected back to the form, you will have access to an error MessageBag. This is what you can use to display your errors within the view.

You can read more about it here:

https://laravel.com/docs/master/validation#working-with-error-messages

Feb
21
3 months ago
Activity icon

Awarded Best Reply on UploadedFile Path, Filename, Basename, Pathname, And Extension Empty On Ubuntu

@alex29

I suspect it's the upload_max_filesize setting within php.ini on the web server. Default is usually 2MB.

 size: 2497377   // over 2MB

the other clue is the mime type:

-mimeType: "video/mp4"  // local
 -mimeType: "application/octet-stream" // server

That suggests that it can't upload the file in its entirety because again of the max upload file size configuration.

Activity icon

Replied to UploadedFile Path, Filename, Basename, Pathname, And Extension Empty On Ubuntu

You might want to check the post_max_size value, too.

I'm almost certain your problem will be one or the other.

Activity icon

Awarded Best Reply on Update The Record If It Exists Laravel

@jgnasser It looks like you have the parameters reversed for the updateOrCreate() method. The first parameter should be the column / value-pairs that you want to locate, the second parameter is what you want updated.

 $rating = Rating::updateOrCreate(
        ['user_id' => $user_id, 'movie_id' => $movie_id], // locate records matching user_id & movie_id
    ['star_value'=>$star_value]  // update the star_value
        ); 
Activity icon

Replied to Search Key By Value Using Collection

@untymage

I think something like this would work:


$search = 'Folk';

$collection->filter(function ($group) use ($search) { 
    return in_array($search, $group); 
})->keys()->first();

Basically filter the collection down to the items that contain what you're searching for and pull the first key. If it doesn't exist, it should return null.

Activity icon

Replied to Update The Record If It Exists Laravel

@jgnasser It looks like you have the parameters reversed for the updateOrCreate() method. The first parameter should be the column / value-pairs that you want to locate, the second parameter is what you want updated.

 $rating = Rating::updateOrCreate(
        ['user_id' => $user_id, 'movie_id' => $movie_id], // locate records matching user_id & movie_id
    ['star_value'=>$star_value]  // update the star_value
        ); 
Activity icon

Replied to Collection Pass Blade

@aronaman The reason why the collection methods don't work, such as pluck, sum and implode is because you're converting your collection to an array within the controller, then passing that array to blade.

Just don't convert to an array.

 $groups=$lists->groupBy('validation_code')->toArray();  // remove ->toArray()
Activity icon

Awarded Best Reply on Laravel Task Scheduler: Managing Tasks Which Take Longer Than One Minute To Execute?

@tgbv Regardless if Cron is calling every minute, you can configure Laravel's Task Scheduler to execute your tasks whenever, or however frequently you desire. If there is nothing scheduled, Task Scheduler will just close and wait for the next call from Cron.

So, if you have a long running script, just make a task entry for something that runs every 2 minutes, or 5 minutes, or however long you think it needs.

For example:

$schedule->command('my-command')->everyFiveMinutes();

Cron can call Task Scheduler to run every minute, but that command will only execute once every five calls.

To answer your question, no it will not kill processes already running.

If the length of time to process is too much of a variable, then you could consider making some kind of process mutex, drop file, or lock-entry in a database to let future processes know that there is a job in progress and to die immediately.. so yes, handle it yourself in some way.