Talinon

Talinon

Member Since 3 Years Ago

Toronto

Experience Points 146,200
Experience Level 30

3,800 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 772
Lessons
Completed
Best Reply Awards 110
Best Reply
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.

18 May
1 week ago

Talinon left a reply on I Need Help.

Most of the criticism towards PHP are from its early years. It still has a few odd quirks, but for the most part it has come a long way.

In fact, Jeffrey Way just spoke about this in a recent podcast: https://laracasts.com/podcast/295690

As for success stories - I fully endorse Laracasts for beginner or intermediate developers. Even senior developers would find some of the specialized courses useful, or for learning the ins-and-outs of the Laravel framework. I can attest to its effectiveness as I believe it has made me twice the developer I was a few years ago.

17 May
1 week ago

Talinon left a reply on Error Unable To Prepare Route [api/user] For Serialization. Uses Closure.

You can't cache routes if you are using a closure. The closure is this part:

function (Request $request) {
    return $request->user();
}

Instead, if you move the code into a controller you'll be able to cache the routes and eliminate the error.

Talinon left a reply on Laravel 5.8 Does Not Use Sqlite For Testing

Have you defined DB_CONNECTION within your phpunit.xml file?

Talinon left a reply on Static Properties On A Model Class

The reason people frown upon public static properties is because it breaks the fundamental concept of encapsulation. When you define a public static property, you're basically just creating a global namespaced variable that can be accessed (or even more concerning, mutated) from anywhere within your app.

When I create a public static property/method, I always ask myself whether or not it makes sense to call a method/property on a class when I haven't instantiated an object. There are times when it does make sense.

In your case, it is likely fine - since you're not dealing with a specific object, but most likely using Eloquent to retrieve a collection of models.

I've done something similar to this in regards to table sorting/filtering/pagination. The first thing I analyzed was how many places within my app I'd need to access the public properties. Once I realized I'd only need to access the public static properties within a single area of the app, I decided to instead declare the properties within the controller. My reasoning was that the controller is what is responsible for deciding what information to gather, so might as well declare it there. Your trait could reference the properties on itself rather than reference properties on outside classes.

You could take this a step further and have the controller implement a contract that ensures that methods are defined that would be used as setters for the properties - but that is totally up to you on how complex you want to make this.

Talinon left a reply on What Is The Best Solution To Generating Export Csv Data (Performance)

I would start off by determining if the problem is with your query, or the CSV export. Install barryvdh/laravel-debugbar and see how long your query is taking. If it's taking the majority of the time, then you need to look at query optimization. Maybe you would benefit with adding some sensible table indices, or only selecting the fields you are using to export. If you have direct access to MySQL, you might want to consider beefing up the server configuration so it has more resources.

If it's not the query, then obviously it's your export iteration. Without seeing any code, it's hard to comment on how you may do it more efficiently.

Is this something that must be generated on-the-fly? If all else fails, consider making a scheduled task that creates an export (such as overnight) that can be downloaded by the user the following day.

11 May
2 weeks ago

Talinon left a reply on Simple Thoughts About Laracasts And Very Simple Issues

Well, it is possible to have videos play in succession - Youtube does it.

However, since we're being philosophical and not technical - I find this to be making a problem out of one that doesn't exist. This reminds me of the first time I saw automated wiper blades on a vehicle, and couldn't help but think how it caters to people whom are too lazy to move their finger one inch to activate it themselves.

On another note - one that may or may not be true - if you have videos playing in succession, the owner runs the risk of increased bandwidth expenses when users start a series, then walk away from the device with it streaming unnecessarily for hours..days?

10 May
2 weeks ago

Talinon left a reply on Unhandled Promise Rejection: TypeError: Undefined Is Not An Object (evaluating 'response.data')

That means you have an error on your back end.. probably a validation error which you're manually catching and returning a 422 response. dd($e) to see what the problem is.

Talinon left a reply on Unhandled Promise Rejection: TypeError: Undefined Is Not An Object (evaluating 'response.data')

@hjortur17 I only skimmed over your code, but I think the reason you're getting that specific error is you're not handling catching the error properly.

For example, if the server has an internal error, there will be no response.data on the error object. For your reference: https://github.com/axios/axios#handling-errors

Open up your browser's developer tools, and check the network tab for the response to get the error message from the server - or console log error.message

08 May
2 weeks ago

Talinon left a reply on First Truthy Callback Result

This is expected behaviour - first() returns the first element within your array that passes the truth test from your callback function.

You could do something like this:

public function calculateDiscount()
    {
        Arr::first([
            ActiveProductDiscount::class,
            ActiveManufacturerDiscount::class,
            ActiveProductGroupDiscount::class,
            ActivePriceGroupDiscount::class,
        ], function ($class) {
            return $this->discount = $class::byStock($this) ?? 0;
        });
    }

In the above, each iteration will set your discount property to zero until it encounters its first non-null value.

01 May
3 weeks ago

Talinon left a reply on Function Outside Component

Yes, I think that would place it within the global scope.

You can test that yourself by just adding something simple like a console.log() or alert() to the component file. It'll be triggered as soon as you load your app.

Talinon left a reply on Jquery Prevent Default Not Working

The problem is the scope within you have declared allowSubmit. Every time your function is called, it's being re-declared to false, which is preventing the default.

Move your deceleration to the global scope:

var allowSubmit = false;

$("#form").submit(function(e){

if (!allowSubmit){
    e.preventDefault();
}

Talinon left a reply on Sum Up An Attribute From Children Components

Oh, I see what you mean.

Someone might have a better solution, but I think your only options.

The first would be to emit an event back to the parent whenever a quantity is selected. Your supplies component could listen for the event and update accordingly.

The second would be to consider using vuex, which is usually overkill.

Another solution MIGHT be vue-portal. I've never personally used it, but it might solve your issue.

Talinon left a reply on Sum Up An Attribute From Children Components

@adamkeen

Getting the total from all the children components would be difficult.

Instead, within your supplies component, create a computed property. I think something like this would work:

computed: {
  total () {

    var sum=0;

    for (supply in supplies)
        sum += supply.price * supply.quantity;

    return sum;


}

Talinon left a reply on Created And Updated Events Are Both Fired For Model::create()

Are you certain that Category::create() is causing both to fire? I find it especially strange that updated would be called before created. I suspect something in your test set up might be triggering an update on another model that is being observed elsewhere. Try dumping $category and confirm?

 public function updated(Category $category)
    {
        dump($category); //This should not be executed.
    }

Talinon left a reply on Vue-js Modal Opens The Both Modals At The Same Time

Of course its launching twice - you have two instances of the same component, making the same call to $modal.show('test')

You need to pass in a prop to explicitly call the modal you want.

Something like this (untested)

<testing modalName="test"></testing>
<testing modalName="hello"></testing>
<template>
    <div>
        <a @click="$modal.show(modalName)">BUTTONS</a>

        <modal :name="modalName" height="auto" draggable=".window-header">
            <div class="window-header">DRAG ME HERE</div>
        </modal>
    </div>
</template>

<script>
    export default {
        props: ['modalName]
    }
</script>
29 Apr
3 weeks ago

Talinon left a reply on Shared Methods In Models

Sounds like a good use for a trait.

trait MakesPath
{

    public function path($subpaths = [])
    {
        $path = '';
        foreach ($subpaths as $subpath) {
            $path .= '/' . $subpath;
        }

        return '/streams/' . $this->token . $path;
    }

}

Then just add use MakesPath; to each of the models you want to have this functionality.

On a side note, unless you have some reason for it, I'd remove the subpaths array and just pass in a string. I don't see any benefit to breaking your path into an array, and it will dry up your code a bit.

For example:

   public function MakesPath($subPath = '')
    {

        return "/streams/{$this->token}/{$subPath}";

    }
<li class="nav-item">
     <a class="nav-link" href="{{ $stream->path('documents') }}">Documents</a>
 </li>

If you needed to dive into deeper subdirectories, just add to the path string:

     $stream->path('documents/subdirectory1/subdirectory2')

Talinon left a reply on Interfaces Again

@mindexperiment You answered the question yourself. What you're trying to do is basic OOP. It has nothing to do with Laravel or its container.

Talinon left a reply on Catching Wildcards In Routes

@MattB

If should match anything after /images/ Do you have any other routes defined before this route that could be catching the request instead?

Talinon left a reply on Catching Wildcards In Routes

@MattbB

You can use a regular expression to match anything after the url:

Route::get('/images/{url?}', function(){
  return 'NOPE';
})->where('url', '.*');

Talinon left a reply on Getting Data Using With() Relation In Controller To Js

@FareedR First of all, -> is a php property accessor and won't work with javascript. Secondly, campusObj.campuses is an array, so you will need to treat it as such.. i.e: campusObj.campuses[0].id

Talinon left a reply on Interfaces Again

The first argument to bind() is essentially just a key. When you pass in Publishable::class, you are just passing in a string representation of the full name spaced class name. You can only have one binding per key - this is why only Comment gets resolved out of the container because you overwrote the first binding.

You don't need to bind into the IOC in order to use an interface. You bind into the IOC if you want to harness the power of swapping out underlying implementations, or for resolving complex classes with a lot of dependencies.

What you posted above would work just fine if you want your Article and Comment models to adhere to the Publishable contract. You have type-hinted the interface in your controller so that you can be confident that whatever gets passed into it will have the methods defined.

20 Apr
1 month ago

Talinon left a reply on ExpectException() Doesn't Work When It Is Catched

expectException() will only return true if the exception thrown is not handled. In your case, since you catch it immediately, the test faIls.

Either change your store method to throw your exception without catching it, or go about your test in a different way.

I realize in this example you're just doing some trial and error, but what exactly do you want to test? What I gather, you don't want to allow Private Profiles to be able to hit the store method.

So - maybe you want to place that logic in middleware, and then test that the user gets denied.

Something like:

public function private_profiles_may_not_create_whatever() 
{

    $this->actingAs($privateProfileUser)->post('/', [])
        ->assertStatus(401);

}

Talinon left a reply on Why MySql Show Number Of Rows 2X After Adding Foreign Key

It shouldn't.. and I can't think of any reason why it would.

How did you go about adding the foreign key? Did you run a migration, or did you execute a MySQL command thru the interpreter?

If you ran a command, what was it, and what did it say for number of rows affected?

12 Apr
1 month ago

Talinon left a reply on 404 Not Found

$cat_name = categories::where('id', $category_id)->firstorFail();

You have this outside of your conditional check on whether$category_id is empty. So, if it is empty (or if the provided category id doesn't exist) then `firstOrFail()`` is going to end up returning a 404.

07 Apr
1 month ago

Talinon left a reply on PHPUnit Throws Error But Works When Specifying The Specific Test

You probably have the same test class name defined in another test file somewhere. This happens to me occasionally if I copy the boilerplate of a test class to a new file and forget to change the class name.

Talinon left a reply on Route Issue

If you run a php artisan route:list, you should see a GET route registered with a URI posts/{post}, which will be a route model binding for your PostController's show() method. So, when you try accessing posts/trashed, you are hitting your show method, and since no there is no Post resource with an id of trashed, you're getting nothing.

If you define your trashed route BEFORE the resource route, it should solve the problem.

31 Mar
1 month ago

Talinon left a reply on How To Catch A "Trying To Get Property Of Non-object Error" In Laravel

It looks like first() has no results, which means you can't access vendor_company on something that is non-existent.

Talinon left a reply on How To Catch A "Trying To Get Property Of Non-object Error" In Laravel

So, your record doesn't have a vendor_company, which means it can't access a property on something that is non-existent.

You need to check for that before trying to access the property, or perhaps you can make the optional() helper work.

Talinon left a reply on How To Catch A "Trying To Get Property Of Non-object Error" In Laravel

Hard to say without seeing any code. It could be anything. A common reason for this error regarding Eloquent might be you are trying to reference a property off a relationship that doesn't exist for your record.. but that is just a wild guess.

Talinon left a reply on How To Catch A "Trying To Get Property Of Non-object Error" In Laravel

Well, that's not a Laravel error, but a PHP error. You'll want to look for something that uses an object property accessor -> on something that isn't an object. Follow the stack trace to lead you to the culprit.

Talinon left a reply on How Do I Become Good At Programming

To quote Einstein:

If you can't explain it simply, you don't understand it well enough.

I'm not saying that you can't learn from reading documentation and code, but I think nothing beats a good teacher. Jeffrey Way is a talented teacher that has a method of explaining things in a way that makes things click. Some people respond better to different styles of learning. Some might excel during lectures, others might need visual aids, other might need things in print. If everything you've tried up to this point hasn't worked, I'd suggest one of the best things you could likely do for yourself is subscribe to Laracasts and watch the dedicated series on TDD.

A couple hours of videos of having someone explain things in simple ways will advance your skills much faster than trying to decipher other developer's (potentially) complex code.

Talinon left a reply on POST And ActingAs Testing Not Working

@damcclean There could be lots of reasons why the test fails. It could be that you don't have a post route defined for /settings, it would be because of failed validation, it could be because you're not returning a redirect response from your controller, or anything else wrong along the way.

What error message are you getting?

Have you dd() the contents of $response to see what message you're getting?

BTW - there is no point in re-assigning the $response variable like you have. You can simplify it by doing:

$response = $this->actingAs($user)->post('/settings', [
            'first_name' => 'John',
            'last_name' => 'Doe',
            'email' => '[email protected]'
        ]);
26 Mar
1 month ago

Talinon left a reply on Sentinel Role Problem

I'm not going to respond to every bewildering thing you've mentioned, just the one thing you decided to quote me and call me out on. Go educate yourself on controller actions:

https://youtu.be/MF0jFKvS4SI?t=360

Talinon left a reply on Sentinel Role Problem

@jlrdw It's not the same thing at all. I don't even know where to begin.

He is asking about middleware. Your whatever-you-call-it, appears to be a method on a controller. The concept of middleware is to prevent the stack from ever reaching the controller.

What the heck is Cln?? If I don't know, how is a novice developer supposed to know? They are just going to paste that in, and wonder why they get a Class not found error.

What is a indexbl? That'll just confuse the person even further.

Why are you using unconventional controller methods? It should simply be index() not indexSomeArbitraryStuff()

Why is user()->role returning some comma-delimited string? Is anyone going to understand that? I sure don't.

Why are you returning a string from a ternary, then evaluating a strict comparison against what you returned, only to return true or false? Just return the result of in_array()? Also, string comparisons are one of the leading causes of slow code.

Talinon left a reply on Sentinel Role Problem

@rostal You can assign middleware to route groups to handle user access.

Routes:

Route::group(['middleware' => 'admin'], function() {
    // admin-only routes
});

Route::group(['middleware' => 'moderator'], function() {
    // moderator-only routes
});

Admin Middleware:


   public function handle(Request $request, Closure $next)
    {

    // deny access if the user is not an admin
        if (!Sentinel::inRole('admin))
        {

        // redirect code

        }


        return $next($request);
    }

Moderator Middleware:

 public function handle(Request $request, Closure $next)
    {

    // deny access if the user is not an admin nor a moderator
    if (!Sentinel::hasAnyAccess(['admin', 'moderator']) {

        // redirect code

        }

        return $next($request);
    }

25 Mar
2 months ago

Talinon left a reply on Subtract Array Value

@vandan You can simplify this quite a bit:


$difference = Registration::where('id','=',$id)->sum('charges') -
            Pay::where('student_id','=',$id)->sum('amount');

Talinon left a reply on Using Mockery, But Original Method Still Being Called

@bwrigley Hmm, there is only 2 things that comes to mind.

My first thought, and probably the least likely, is make sure you have imported IntercomGateway into your test file, otherwise by default, you'll be mocking & binding Tests\IntercomGatewayinto the container and hence leaving your original implementation untouched.

My second guess would be that you're not resolving it properly from within your application code. Can you show the code where you actually resolve IntercomGateway and make the call to createUser()?

24 Mar
2 months ago

Talinon left a reply on How To Run A Decent SetUp() In Laravel Dusk

Try adding a void return type:

 public function setUp() : void

Talinon left a reply on Is There A Way To Persist Certain Tables Between Tests?

@alexgodbehere php artisan migrate --database=mytestingdatasename

Talinon left a reply on Is There A Way To Persist Certain Tables Between Tests?

You might want to consider using the DatabaseTransactions trait. You can seed your database once, and DatabaseTransactions will still roll back the test transactions at the end of the tests, but won't run the migrations; meaning your seeded data will persist thru the tests. The only thing you need to be mindful of, is you will need to manually run the migrations on your test database to bring them up-to-date when you make changes to your database structure.

22 Mar
2 months ago

Talinon left a reply on Where To Use Vue In Laravel

@kinsaw88 what you are referencing is a View component, which you would need to register as a component for Vue to mount.

Instead of trying to go into great lengths to explain, I would suggest watching the entire free series on Vue. You'll be taken by the hand and shown every step of the way.

https://laracasts.com/series/learn-vue-2-step-by-step

Talinon left a reply on How To Remove Item From Cart Through Session Laravel 5.6?

@mubeenali Did you write the original Cart code above, or are you editing an existing project?

Talinon left a reply on Using Mockery, But Original Method Still Being Called

There seems to be a problem with return types and previous versions of Mockery. Most likely because the version of Mockery you are using is based upon a PHP version that didn't support return types.

Talinon left a reply on How To Remove Item From Cart Through Session Laravel 5.6?

@mubeenali There is no short-cut to just remove it from the session - because how is your qty and prices supposed to update?

You need to pretty much do the same thing you're doing when you're adding to your cart.

Get the cart from the session, instantiate your Cart class with the session data, call a method that handles the remove logic, and then put it back into the session.

Talinon left a reply on How To Remove Item From Cart Through Session Laravel 5.6?

Unsetting the product from your Request object isn't going to remove it from the session.

It looks like you might want to add a remove() method to your Cart class, and then update the session?

Talinon left a reply on Using Mockery, But Original Method Still Being Called

Try removing the return type:

From:

public function createUser(User $user): void

To:

public function createUser(User $user)

Talinon left a reply on Using Mockery, But Original Method Still Being Called

Do you have final defined on your createUser() method in your IntercomGateway class?

Talinon left a reply on Using Mockery, But Original Method Still Being Called

Yes, you should get 'mocked' as a response. I'm not sure why you would get ``null`

I just tested it using the following, and I get 'mocked`

        $mock = \Mockery::mock('someclass')->makePartial();
        $mock->shouldReceive('createUser')->andReturn('mocked');
        $this->app->instance('someclass', $mock);

        $gw = resolve('someclass');

        dump($gw->createUser(new \App\User));        

Talinon left a reply on Using Mockery, But Original Method Still Being Called

@bwrigley You are still instantiating an instance of IntercomGateway directly in your test:

$gw = new IntercomGateway;

If you resolve it out of the container, it should work:

$gw = resolve(IntercomeGateway::class);

dump($gw->createUser(new \App\User));