Talinon

Talinon

Toronto

Member Since 2 Years Ago

Experience Points 77,010
Experience
Level
Lessons Completed 485
Lessons
Completed
Best Reply Awards 46
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

12 Nov
23 hours ago

Talinon left a reply on Strange Behavior On Event Trigger And Listener

I have added a log in the FoodCreated constructor to see whether it is initialized or not

The queue worker loads your code base into memory at the time of running it. Are you aware that you need to restart your queue worker whenever you change your code base?

Try running: php artisan queue:restart

Talinon left a reply on Strange Behavior On Event Trigger And Listener

Have you imported FoodCreated in your second controller?

09 Nov
3 days ago

Talinon left a reply on Non-static Method Lavary\Menu\Menu::make() Should Not Be Called Statically

Also, remember to remove the 'use Lavary\Menu' line at the top, if it's there.

Or try ``\Menu::make(...)``` to make sure you're using the alias.

Talinon left a reply on Non-static Method Lavary\Menu\Menu::make() Should Not Be Called Statically

My guess is that you haven't set up the facade alias and are trying to call the class directly.

Have you added this to your config/app.php file?

'aliases' => [
    ...
     'Menu'      => Lavary\Menu\Facade::class,
...
];
07 Nov
5 days ago

Talinon left a reply on Add User_id To A Guarded Model

@CRNKOVIC - It has nothing to do with the number of users, rather it uses the currently authenticated user; which may be fine, depending on the app. Snapey was stating that it may not be the best solution, IF you have the need to assign it to another user other than the one submitting the request.

There are plenty of ways to go about it.

Another option is to use forceFill() at an explicit end point, which forces the attributes to be mass assigned.

04 Nov
1 week ago

Talinon left a reply on Code Returning False

I would also suggest things like this to be broken into separate methods, and naming them something more comprehensible. It helps the readability of the code, especially if you come back to this 6 months later.

For example, imo, this is much easier to read:

    if (! ($this->isDoctor() && $this->isStaff() && $this->isPatient()))
    {
        abort(403, 'You cannot view this appointment');
    }

protected function isDoctor() : Bool
{
    return $this->doctors->contains(Auth::user()->id);
}

protected function isStaff() : Bool
{
    return $this->appointment->staff_id;
}

protected function isPatient() : Bool
{

    return $this->apppointment->patient_id == Auth::user()->id);
}

``

You might have to pass some parameters into the methods, or set some class properties, but you get the idea..

Talinon left a reply on Code Returning False

If you want the 403 only to be triggered when NONE of the clauses are true, then you need to rewrite it to something like this:

    if (!$doctors->contains(Auth::user()->id) &&
         !$appointment->staff_id &&
         $appointment->patient_id !== Auth::user()->id)
         {

             abort(403, 'You cannot view this appointment');

         }

Talinon left a reply on Saving To Eloquent Relationship

If you basically want to mirror the data into other tables, you might want to consider setting triggers on your table within the database. One use case I have for this is when I want to store revisions of records. You can make a trigger for creates, and another for updates, and have whatever fields you wish inserted to another table.

If you don't like that approach, there is nothing stopping you from just making separate create calls per relationship?

Talinon left a reply on Add User_id To A Guarded Model

It's ok, you're not really override the core, but just hooking into the model events. For updates, you can similarly use the static upading() method:

 protected static function boot()
    {

        static::updating(function ($model) {

        $model->user_id = auth()->id();
            
        });    
    

    }

Talinon left a reply on Add User_id To A Guarded Model

I handle these situations in a couple ways. I usually add the user_id to the $fillable array, but ensure it always gets overridden either in the controller, or the model's creating() static boot method.

Controller method:

$request['user_id'] = auth()->id();
$model->create($request->all());

Model method:

    protected static function boot()
    {

        static::creating(function ($model) {

        $model->user_id = auth()->id();
            
        });    
    

    }

28 Oct
2 weeks ago

Talinon left a reply on Problem With API Tests

Try this


$response->assertJson([
    'data' => [
        $country->only(['name', 'abbreviation'])
    ]
]);


27 Oct
2 weeks ago

Talinon left a reply on How To Run Set Of Tests In Cron ?

If you are speaking about unit testing, I don't know of any tool to handle this. Although, I imagine you could just make use of the ``onNotSuccessfulTest'' method, which should fire for every failed test.

Something like:


    protected function onNotSuccessfulTest(\Throwable $e)
    {

        Mail::send('emails.testFailed', ['exception' => $e], function($message)
        {
            $message->to('[email protected]', 'Admin Name')->subject('Test Failed');
        });        
    }    


You can handle all the formatting for the email within the view. You could place the above code in your BaseTest class, or into a Trait which you could use only on the test files you want this functionality.

Then just set up your cron job to run the test suite.

You'd also probably want to consider adding an environment check, so you're not constantly sending out emails upon failures when writing tests.

Talinon left a reply on How To Remove JavaScript Unction After Ajax Page Change

I can't see this being the best approach to prevent the re-execution of a function by deliberately trying to cause an error.

Why not handle with a conditional check using a boolean?

let allowMoreData = true;

function loadMoreData(page) {

   if (!allowMoreData) return;

   ...

}

or something along those lines.

Talinon left a reply on Receiving SMS IN Laravel

I would suggest looking into Nexmo, which you can easily integrate with.

www.nexmo.com https://github.com/Nexmo/nexmo-laravel

26 Oct
2 weeks ago

Talinon left a reply on Validation Form

What is the error, and how do you know it's coming from the validation?

The very first thing I notice is that you don't have your Activites class imported at the top of the file, which would result in a 'class not found' error because of the namespace (if does make it past validation)

25 Oct
2 weeks ago

Talinon left a reply on Display Image From Storage Directory

have you run the php artisan storage:link command?

Talinon left a reply on Laravel Eloquent Event Not Triggered When Model Is Touched

The idea behind touching the parent is just to update the timestamps. I think the timestamps are exempt from a model that has been considered to have updated values, which is why your boot method doesn't fire.

For whatever scenario you're trying to make this work, It looks like you might need to explicitly call a method on your parent model.

12 Oct
1 month ago

Talinon left a reply on Logout (site Data Getting Cleared) Right After Login, If User Not A Developer?

I don't use Spark, but I recently had a similar problem when I was required to update the session domain configuration. Even after deleting all the session data, a user would be immediately logged off after signing in. Clearing the browser cookies would solve the issue on a per-user basis. Ultimately, I ended up creating a new session cookie name to avoid having to clear cookies for every user.

Not sure if that is your problem, but if you've changed anything with your session configuration, might be worth trying.

Talinon left a reply on Mail Queue Does Not Work

Do you see entries in your jobs table in the database?

If so, it sounds like it just might be a matter of running a queue worker. A queue worker is responsible for processing the jobs as they enter the queue.

Laravel come with a build-in queue worker - try running: php artisan queue:work and see if the emails are processed?

You can read more about queue workers here:

https://laravel.com/docs/5.7/queues#running-the-queue-worker

10 Oct
1 month ago

Talinon left a reply on Hi! Hope You Are All Doing Well I Just Need Some Little Help For Testing Unit.

Getting into unit testing is definitely the right approach. I'm afraid you're not using assertions correctly, however. By definition, an assertion in programming is an expression that should always return true at a specific point in the program - otherwise you have a bug.

The first thing I notice is your assertion against $category - not sure what you're trying to do here, because you never initialized that variable.

To take your first test, it might make more sense if we rewrite it like this:

public function testShouldCreateCategory()
    {
        $response = $this->json('POST', '/course_discovery/api/v1/categories/create', 
            [
                'category_name' => 'Klean',
                'category_description' => 'Tumbler', //This should not create same category name.
            ]);


    $response->assertJson(['created' => true]);

    }

In the above test, you are assigning $response' to the response of the API call. Calling theassertJson()` method on the $response object will confirm that response returned by the application contains the properties within the array provided.

This test will assert that the API will return a property identifying that it was created, but it doesn't really test whether or not it WAS created. You may wish to create an additional test to assert that the database contains the new resource.. or you could just add it to the end of this test (some would argue that you should only have a single assertion per test)

You could use something like this to make sure the application actually stored the request to the database:

    $this->assertDatabaseHas('your-table', [
        'category_name' => 'Klean',
        'category_description' => 'Tumbler'
    ]);

If it returns false, it didn't save. If it returns true - you're good. As a side note, you should write this test before you actually write the application code. The test will obviously fail - but the failure messages will guide you to write the production code. You keep running the test after each error, until you eventually get a pass. This is what is known as "Test Driven Development (TDD)". This teaches you to never write production code that isn't driven by a test - which results in your code being 100% supported by tests.

As for your comment that "This should not create same category name", you could create another test which submits the same request twice, and then make an assertion that the database only contains 1 record for that name/description.

Hopefully this helps you better understand how assertions work. It is a bit overwhelming at first, but the value of tests are worth learning this skill - keep up with it. There is also some great lessons on here about unit testing which I suggest you watch. Jeffrey can explain things a lot better than I can - it's totally worth the 9 bucks.

24 Sep
1 month ago

Talinon left a reply on Share Laravel Models In Multiple Apps

First thing I noticed is you're not using a vendor/package convention for your package, which I would suggest. Also, you should have double trailing slashes after your psr-4 namespace prefix

{
  "name":"vendor-name/database-models",
  "autoload":{
    "psr-4":{
      "DbModels\":"src/"
    }
  }
}
use vendor-name\DbModels\Models\Database\Post;

When I was trying to do something similar as you, I found this resource to be very helpful:

https://laraveldaily.com/how-to-create-a-laravel-5-package-in-10-easy-steps/

30 Aug
2 months ago

Talinon left a reply on Handling Major Feed Import Timeout Issues

You are correct in your thinking that importing the elements to the database using a bulk query is significantly faster than inserting a single record at a time. From what you've provided, I would be inclined to think the bottleneck might be in the first step, where you are reading the XML file. How long does the script take if you exclude the ProcessFeed::dispatch() job?

29 Aug
2 months ago

Talinon left a reply on Factory Inside Factory, How To Pass Attribute For All Nested

I haven't tested it, but I think something like this would work:

$factory->define(\App\Comment::class, function (Faker $faker, $overrides) {
    
   $word = $overrides['word'] ?? $faker->word;

    return [
        'rand_string' => $word
        'post_id' => function(){
            return factory('App\Post')->create(['rand_string => $word])->id
        }
    ]

}

$factory->define(\App\Post::class, function (Faker $faker, $word) {
    
    return [
        'rand_string' => $word ?? $faker->word
    ]

}

Talinon left a reply on Factory Inside Factory, How To Pass Attribute For All Nested

$factory->define(\App\Comment::class, function (Faker $faker) {
    
$word = $faker->word;

    return [
        'rand_string' => $word
        'post_id' => function(){
            return factory('App\Post')->create(['rand_string' => $word])->id
        }
    ]

}

$factory->define(\App\Post::class, function (Faker $faker, $word) {
    
    return [
        'rand_string' => $word
    ]

}

Talinon left a reply on How Do You Logically Group Tests For A Resource?

This is something I often question myself, too.

I think it comes down to a question of what makes the most sense for the project? If it is a fairly simple CRUD resource, does it make sense to break up a dozen tests into 6 different test classes? I would argue: no, it doesn't make sense.

Personally, I try to keep them all included into a single class, and have that entire class read like documentation for the resource. Admittedly, I have some test classes that probably have 50+ tests, but I don't see the harm in that, as long as they're all tests for the same feature. We're talking about tests, not production code - I don't think it's something to be overly concerned about.

I sometimes use the setUp() method as a guide for when to break tests up into other classes. If I find that I'm unnecessarily running a lot of setup code for tests, that might be an indication they should be moved into a test class that has less setup work (or more appropriate setup work).

For the class name itself, I usually just keep it simple and use the convention of <Resource-name>Test. If I'm creating a class that tests something beyond the scope of a single resource, or integration tests, that is when I usually decide to create a new test class, and I'll name it something along the lines of Test. can even be several words, to make it clear what the test class is responsible for.

28 Aug
2 months ago

Talinon left a reply on AssertHasOldInput() Missing Since 5.4

Well, I'm not sure what happened, but the guides states it makes every effort to document every change, but sometimes minor or obscure changes get missed.

The source for the assertHasOldInput() was basically just a helper function, so you could always add this as your own helper. You could even place it within your base TestCase.php file.

/**
     * Assert that the session has old input.
     *
     * @return void
     */
    public function assertHasOldInput()
    {
        $this->assertSessionHas('_old_input');
    }
27 Aug
2 months ago

Talinon left a reply on Global Partial Routes On Resources

You should be able to do this:

Route::resource('breeds', 'BreedsController', ['only' => ['index', 'store', 'show', 'update', 'destroy']]);

]);
21 Aug
2 months ago

Talinon left a reply on CURL Error 6: Could Not Resolve Host

Can you show the code where you instantiate $http?

Talinon left a reply on No Debug Page ( Debug Is True )

i already ran cache:clear command ..still getting the same results

It was suggested you run php artisan **config**:clear - just want to make sure you're aware there are two separate commands.

20 Aug
2 months ago

Talinon left a reply on No Debug Page ( Debug Is True )

It may be because of your default file permissions. Check the storage/logs/laravel.log file to see what the last error was. If there is nothing written to the log, then it is almost certainly due to permissions on your storage/directory.

18 Aug
2 months ago

Talinon left a reply on Factory Each Closure With Belongs To Relation

You are associating a Contact instead of an Address:

 $e->address()
            ->associate(factory(Address::class)
            ->make());

Talinon left a reply on Factory Each Closure With Belongs To Relation

I don't see anything immediately obvious that would be a problem. What doesn't work about it? Does it throw an error? or does it just not set the foreign key?

What is the code for your address relationship on your Employee model? Does it return a BelongsTo relationship to the Contact class?

Talinon left a reply on Multiple Middlewares Do Not Work As Wanted

You might find it more convenient to define your middleware on your routes, or to route groups. I prefer this, opposed to adding them to all the controller constructors.

https://laravel.com/docs/5.6/routing#route-group-middleware

16 Aug
2 months ago

Talinon left a reply on How To Use NotIn Function And Case Insensitive Together?

You should be able to do something like this:


'keyword' => [Rule::unique('groups')->ignore($group)->where(function ($query) use ($group) {
                return $query->where('org_id', '=', $group->org_id);
            }),
            function($attribute, $value, $fail) {
                     if (strtolower($value) === 'cancel') {
                                return $fail("Keyword 'Cancel' is invalid");
                            }
                        },
            ]

If you are going to have a re-use for the closure, you can always extract this to its own custom Rule object.

15 Jul
3 months ago

Talinon left a reply on URL Rewrite

First, for the routes, even though I don't think performance would take a hit, I'm sure you could consolidate them with a required route parameter.

Something like:

Route::get('/module/lesson/{page}, '[email protected]');

Then within your LessonController, you can render the appropriate page.

public method show($page) {
    return view("module.lesson.{$page}");
}

As for not allowing your users to jump ahead, you have a few options.

I You might be able to handle this as simply as with a session variable. In the LessonController, update a Session variable that is responsible for keeping track of the last page the user has completed. When the user requests a new page, check to make sure it isn't greater than lastpage+1, otherwise handle it with some kind of exception, redirect, etc. This method may be a more appropriate option for a timed-lesson. The disadvantage is that if the user logs off, the session variable would be cleared, and they would need to start over.

If you want to avoid the session option, then you'd need to resort to some kind of persistence: either to a database, or perhaps a in-memory data store like Redis. If you don't have a lot of traffic, using the database might not be a terrible option.

14 Jul
3 months ago

Talinon left a reply on URLs For Controller Actions With Parameters With Form Submit

I would suggest going thru the excellent free series that this website provides.

https://www.laracasts.com/series/laravel-from-scratch-2017

Talinon left a reply on Best Practice For Handle Edit Requests When User Is Not Exist

Well, another option would be Route Model Binding.

routes.php:

Route::get('users/edit/{user}', '[email protected]');

UserController:

use App\User;

public function edit(User $user)
{

    $roles=Role::pluck('name','id');
    return view('manageuser.edituser',compact('user','roles'));
}

By type-hinting the User Model in your controller function, it will automatically bind the User model using the id. If the user doesn't exist, it will throw a HTTP 404 error (not found). This essentially does the same thing you're trying to do above, but in a much cleaner fashion.

If you don't want to have the error to default to a 404 error page, you will need to catch the ModelNotFound exception. You can read more about that here:

https://laracasts.com/discuss/channels/general-discussion/where-to-handle-404-for-route-model-binding-when-model-not-found

13 Jul
4 months ago

Talinon left a reply on Queue:work Not Responding

Yeah, I figured it was because of a named queue. You can also process them by specifying the queue name: ``` php artisan queue:work --queue=emails``

Talinon left a reply on Queue:work Not Responding

Does the 'queue' column on your jobs table have 'default' for the values?

Talinon left a reply on Queue:work Not Responding

Since Laravel 5.3, the queue:work defaults to daemon mode, so it is behaving properly. If you specify the ''--once'' option, it will process the first job that comes along and then self-terminate. If you want to fork it into the background when you run the command, just add an & to the end of the command: php artisan queue:work &

10 Jul
4 months ago

Talinon left a reply on Update With Save() Doesn't Work

Do you have a primaryKey specified on your model?

protected $primaryKey = 'someColumn';

Talinon left a reply on Update With Save() Doesn't Work

Are you sure you are actually getting a DeliveryTime record with your where condition? Try firstOrFail() to check?

$deliveryTime = DeliveryTime::where('key','=',$key)->firstOrFail();

Talinon left a reply on Queue Job Is Not Finishing

From Laravel 5.2 to 5.3, there were some database changes to the jobs table. You might want to look into that section of the upgrade notes under "Database driver changes" to see if that is your issue:

https://laravel.com/docs/5.3/upgrade

09 Jul
4 months ago

Talinon left a reply on How To Use Mockery For A Class Used In A Controller?

I think you're under the impression that Mockery wields some magic where it can alter your source code with a mock. This is not the case - your test post will still execute your source code exactly as you have it.

Instead, in your test, you can swap out the underlying Newsletter class by calling swap() on the facade.

use Spatie\Newsletter\Newsletter;
class NewsletterTest extends TestCase {

    use RefreshDatabase;

    public function setUp()
    {
        parent::setUp();
    }

    public function tearDown() {
        \Mockery::close();
    }


    /** @test */
    public function a_guest_can_subscribe_to_newsletter() 
    {

    $mock = \Mockery::mock(Newsletter::class)->shouldReceive('subscribePending')->once();  

    \Newsletter::swap($mock);

        $this->json('post', route('newsletter.store'), ['email' => '[email protected]'])
             ->assertStatus(201);
    }
}

The above test will swap your underlying Newsletter class with a mock (for the duration of the test), that expects the function subscribePending to be called exactly once. If the function doesn't get called, Mockery will throw Mockery\Exception\InvalidCountException

Keep in mind, this does not test anything, other than the fact that at some point in your stack, Newsletter::subscribePending() gets called.

You could do the same with a service provider, or anything bound in the Laravel Service Container.

    $mock = Mockery::mock('someClass'); // chain on method calls
    app()->instance('someClass', $mock); // bind the mock object into the Service Container

Now whenever 'someClass' gets resolved out of the Container, it will be your mock, not your source object.

Hope this helps you better understand how Mockery works.

08 Jul
4 months ago

Talinon left a reply on Validate Form Served Via AJAX Call Using JQuery Validation

I think what is going on is when you replace the login form within the DOM, the original elements that have event listeners are removed. When you replace it with the 2fa content, JQuery doesn't have event listeners attached to the freshly added content.

Perhaps you can solve this by wrapping the 2fa form query javascript into a function, and then call it in your AJAX success function.

Something like:

// 2fa form jQuery
function 2fa(
    $(document).on('click', '#submit-btn', function (e) {
        ....
        ....

    });
);
          success: function(data) {
                console.log(data);
                if (data.intended) {
                    window.location.href = data.intended;
                } else {
                    $("#content").html(data.content);
            2fa();  // load event listeners for the new content
                }
            },
06 Jul
4 months ago

Talinon left a reply on Collection Property Does Not Exist

When you get a collection from a model, you're getting an eloquent collection, which allows you to access the data as object properties. When you use collect(), this is a support collection, and is a bit different.

For a support collection, you can use get()

Such as: collect(['one' => 1, 'two' => 2, 'trhee' => 3])->get('one');

04 Jun
5 months ago

Talinon left a reply on Validating JSON API Request With Laravel 5.6

The problem is with your validation rule array. Try this:


$validator = Validator::make($request->json()->all(), [
            'code' => 'required',
            'description' => 'required',
        ]);

31 May
5 months ago

Talinon left a reply on Favorite Testing Methodology?

@jlrdw Even though interesting, your link is regarding NASA Test Pilots :)