Talinon

Talinon

Member Since 3 Years Ago

Toronto

Experience Points 148,710
Experience Level 30

1,290 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 779
Lessons
Completed
Best Reply Awards 113
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.

19 Jul
3 days ago

Talinon left a reply on In Shared Hosting Environment, How To Hide .env File From Public?

Listen, I know you're trying to help.. but, you constantly reply with irrelevant, misguided information. You reply to random things, often incorrectly, and then argue over it for as long as someone has the endurance to keep up with you. Even when proven wrong, you still keep it up with long-winded replies trying to prove some obscure point that no one cares about.

Perhaps my reply was unprofessional, and I apologize for that. Although you just proved my entire point.

You've been triggered for hours over this. Drop it and move on.

Talinon left a reply on In Shared Hosting Environment, How To Hide .env File From Public?

@jlrdw

You're right. I should stay on topic. I'm unable to provide any further advice on .env security that isn't already answered by your join query. Thank you for clearing up the thread's topic with that relevant code snippet.

Also, I should thank you for clarifying that .env should only be used in development environments. Honestly, I had no idea. I guess I'll remove the .env file from all production servers and hard-code everything in the configuration files and commit those changes to version control. Does that put me back on the right track?

Talinon left a reply on In Shared Hosting Environment, How To Hide .env File From Public?

Incoming story on a Logistics company or some random pet code.

10 Jul
1 week ago

Talinon left a reply on Mockery Executing Original Method

@bwrigley

I have zero experience with Cashier, but this thread might be of use to you: https://laracasts.com/discuss/channels/testing/how-to-mock-a-user-with-a-cashierstripe-subscription

To return to your original question - yes, I'm aware it's part of your code base.

A lot of developers new to mocking have some incorrect notion that mocking something performs magic and automatically transforms your code base. It does not. In your test, you are creating a mock for $plan, but your base application doesn't have any knowledge of your mocked object. It doesn't dive into your code base and transform any reference to Plan to your mocked object. Whether your controller is invoked by live or a test, it's still going to give you a new object of Plan.

You did bind your mock into the container, which is fine, but you're still not resolving it when you're referencing Plan. That is why I said if you use resolve() it'll do what you expect. As @johnbraun mentioned, this isn't the best approach, but I was trying to answer why your testMethod() wasn't behaving as you expected.

Talinon left a reply on Mockery Executing Original Method

@bwrigley

I think the problem is here:

$plan = Plan::whereNickname($request->plan)->first();

You are retrieving a model instance by directly referencing Plan instead of the instance in the container. Try this instead:

$plan = resolve(Plan::class);

// or

$plan = $this->app->make(Plan::class);

dump($plan->testMethod());

Make sure you import the full namespace for Plan in both your test and the class you resolve it in.

09 Jul
1 week ago

Talinon left a reply on How To Return Validation Error When It's Failed

@mostafalaravel

It looks to me like you're using AJAX, so Laravel will return your errors in a JSON response.

To quote the documentation:

When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

This should work automatically - check for the errors object in the response.

Alternatively, if you want more control (which usually isn't necessary) you can manually handle your validation. You can read more on that here: https://laravel.com/docs/5.8/validation#manually-creating-validators

27 Jun
3 weeks ago

Talinon left a reply on Get The Currently Active Queue Workers

Well, you can configure how many queue workers are active. If you want more control, you could set up a particular queue dedicated for downloads. Then you could assign a number of queue workers you want dedicated to that specific queue.

dispatch((new Job)->onQueue('downloads'));

Then configure supervisor..

command=php /path/to/artisan queue:work  --queue=downloads ...
numprocs=2

https://laravel.com/docs/5.8/queues#customizing-the-queue-and-connection

https://laravel.com/docs/5.8/queues#supervisor-configuration

You could also install Horizon to monitor your application queues (if you're using redis)

Talinon left a reply on Error Log Saying No Query Results Found But There Are Records

If you're using the SerializesModels trait, only the id of the eloquent model will be serialized. When the queue is run, Laravel will automatically retrieve the model from the database by the id.

You might want to consider ignoring missing models. You can read more about that here:

https://laravel.com/docs/5.8/queues#ignoring-missing-models

Talinon left a reply on Error Log Saying No Query Results Found But There Are Records

@chrisf79

$class = 'App\Models\TempListing' . $feed->board;

Maybe add the preceding slash?

$class = '\App\Models\TempListing' . $feed->board;

Talinon left a reply on Error Log Saying No Query Results Found But There Are Records

@chrisf79 You are dispatching the job into a queue - have you restarted your queue worker(s) since the last code change?

To quote the Laravel documentation:

Remember, queue workers are long-lived processes and store the booted application state in memory. As a result, they will not notice changes in your code base after they have been started. So, during your deployment process, be sure to restart your queue workers.

26 Jun
3 weeks ago

Talinon left a reply on Where To Put Local Scope In Many To Many Scenario

@boneill81

You could just add a method like this to your user model:

public function adminGroups()
{

    return $this->userGroups()->wherePivot('user_role_id', 2)->get();

}

Then you could just call $user->adminGroups()

Failing that, I think you could make a scope using a join.. something like this:

public function scopeIsAdmin($query)
{

    $query->join('user_group_users', 'users.user_id', '=', 'user_group_user_id')->where('user_group_users.user_role_id, 2);

}

Talinon left a reply on Where To Put Local Scope In Many To Many Scenario

@boneill81

Try this:

Auth::user()->userGroups()->wherePivot('user_role_id', 2)->get();

Talinon left a reply on Automatic Backup Is Not Working

@zaster

Have you checked to make sure the cron service is running?

service cron status ps aux | grep cron

Maybe check system logs for any possible errors: /var/log/syslog

Also, make sure you are adding the crontab entry under the correct user account that your project runs under.

Talinon left a reply on Where To Put Local Scope In Many To Many Scenario

@boneill81

The reason Auth::user()->userGroups->isAdmin() doesn't work is because when you call Auth::user()->userGroups you are getting a collection, and isAdmin() is not a method on a collection.

If you only want to get a collection of UserGroups that a user is an admin, you should be able to just chain it like so:

Auth::user()->userGroups()->isAdmin()->get();

19 Jun
1 month ago

Talinon left a reply on Using Transactions In Laravel User::Create For Setting User Role

@repulsor I would think something like this would work:

protected function create(array $data)
{
    return DB::transaction(function () use ($data) {
    $NewUser = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'phone' => $data['phone'],
        'password' => Hash::make($data['password']),

    ]);
//    $row_id = $this->create($data)->id;
    $UserRole = UserRole::create([
        'user_id'=> $NewUser->id,
        'role_id' => 1,
    ]);

    });
}

Talinon left a reply on Using Transactions In Laravel User::Create For Setting User Role

You can make the anonymous function inherit $data by using the use keyword:

return DB::transaction(function () use ($data) {

    ...


11 Jun
1 month ago

Talinon left a reply on Problem With Method Not Allowed Exception

@cronix ah, okay. I didn't realize (or forgot) that package automatically adds the spoof.

Talinon left a reply on Problem With Method Not Allowed Exception

@Snapey Regardless of it being a Resource Controller, HTML forms still only accept GET or POST. A spoof is still needed.. or am I missing something?

To quote the documentation:

Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs. The @method Blade directive can create this field for you

Talinon left a reply on Problem With Method Not Allowed Exception

@morbakos You can't use a method of 'PUT' within your HTML form tag, it is not a valid HTTP form verb. Instead, you can spoof PUT by using a blade helper method to place a value in your request that Laravel will understand. Change the method from PUT to POST

Try this:


{!! Form::model($mission, [route('missions.update', $mission->id_missions), 'method' => 'POST', 'class' => 'form-horizontal panel']) !!}

    {{method_field('PUT')}}

    ....



Talinon left a reply on Testing Json And Enum Column Types With Sqlite

Do you have a very good reason for using ENUM data types? They can be completely avoided under most scenarios. I would consider dropping them and going with a more standard approach using a reference table.

I could list a bunch of web links that speak about why you should avoid using ENUMs, but a google search would do that for you.

If all the reasons against using ENUM are not enough, then the fact you can't use an in-memory SQLite database should be reason enough to ditch them.

01 Jun
1 month ago

Talinon left a reply on It Seems Like Laravel Boot Trait Doesn't Work

@agilasadi Do you have boot() defined on your model(s) as well? If so, I'm pretty sure it'll completely override your bootable trait, unless you add parent::boot()

18 May
2 months 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
2 months 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 months 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 months 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 months 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
2 months 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
2 months 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
3 months 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
3 months 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
3 months 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
3 months 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.