Talinon

Talinon

Member Since 3 Years Ago

Toronto

Experience Points 157,130
Experience Level 32

2,870 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 820
Lessons
Completed
Best Reply Awards 120
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.

10 Aug
1 week ago

Talinon left a reply on Override Boot Function When Insert Function Calling In Laravel

@vaibhavsinghal

The problem is that insert() is not a model function; the model is never retrieved so there is no event.

The reason you can use ModelName::insert() is because you end up with an instance of Query Builder due to some magic calls. Since Builder will directly insert into the database, you never have an actual model instance.

You shouldn't need to use insert() unless you're dealing with mass/batch inserts. In that case, you'll have to write your own logic to dispatch your own events.

Talinon left a reply on Laravel Throttle

@mailnike

I had this problem once dealing with webhooks with a custom ERP integration.

You could create your own middleware group for the webhooks and either exclude the throttle middleware within your app/kernel.php, or increase the number of requestes allowed:

You might just be using an umbrella 'api' middleware group:

'api' => [
    'throttle:240,1'  // allow 240 requests per minute to api group
]

disable all throttling for shopify:

'shopify' => [
    // 'throttle:60,1'
]

You could also add throttling on specific route, or a group of routes:

->middleware('throttle:120,1');


Route::group(['prefix' => 'webhooks', 'middleware' => 'throttle:120,1'], function () {
    Route::get() ....
    Route::get() ....
});



But in the case of applying it to a single route you'd want to make sure the route is not part of a middleware group that has the throttle middleware applied or it would still be in effect for each request. In other words, it won't override it.

As for the cons of completely disabling throttling, your application simply won't rate limit incoming requests.

09 Aug
1 week ago

Talinon left a reply on Checkbox Value

@hjortur17

You're bouncing all over the place with different questions. I would suggest to just take a step back and soak in some tutorials to help you overcome the confusion. Start with this series to better acquaint yourself with the framework:

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

As for your Access-Control-Allow-Origin error, review this video:

https://laracasts.com/series/laravel-vue-and-spas/episodes/7

Talinon left a reply on Syntax Error, Unexpected '(', Expecting Identifier (T_STRING) Or Variable (T_VARIABLE) Or '{' Or '$'

@andreas94

Looks like you're missing a function call, a where condition perhaps?

if (GDPR::where('id_user', Auth::user())->where('type', '1')->exists())

Talinon left a reply on Checkbox Value

@hjortur17

It has nothing to do with the number of checkboxes. A million checkboxes would not fix this problem. I don't think you're understanding the security issue we're trying to make you aware of.

Let's say you have a website up and running on the web. I could literally use a command line to send a POST request to your API with whatever data I want. You do NOT want your application to just accept whatever price is given to it from the front-end. Unless of course it's an administrator setting prices, but I don't think that is the issue here.

Instead, you could pass thru an array holding the IDs of the services that the user selected with the checkboxes. Then in your backend, you'd fetch the true selling price from your database.

I have really no idea what your application logic is, but to try to give you a basic idea...

I assume you're using laravel, so something like this:

public function store(Request $request) {  

    // assuming you have already handled validation...

    $items = Item::whereIn('id', $request->services)->get();  // get all items the user selected

    // or maybe something like this:

    $totalPrice = Item::whereIn('id', $request->services)->sum('price');  // get sum of prices of items selected

}

Talinon left a reply on PHPUnit Returning 404 After First GET Request

@pedroroccon

Awesome, I'm glad that fixed your issue. I remember that being a head scratcher for me, too.

Probably a better way of going about adding multiple route files, opposed to using require within your web,php, is to add your additional route files within the RouteServiceProvider

This blog speaks about it, and it's exactly how I go about doing it:

https://medium.com/@ntimyeboah/how-to-add-a-custom-route-file-in-laravel-93a087c62424

Talinon left a reply on File Upload Limit Issues

@mattb

Do you have a maximum size rule in the form validation? Perhaps failed validation is causing a redirect and you're not outputting the errors to the page?

Talinon left a reply on File Upload Limit Issues

@mattb

Yes, within the php.ini file.

No errors? Nothing in the laravel log? What about the web server log?

You could also try bumping the memory_limit a bit higher than the default. To my understanding this shouldn't really affect file uploads because they shouldn't be fully stored in memory, but rather in chunks as it stores to the disk.. but worth trying.

Talinon left a reply on File Upload Limit Issues

@mattb

Perhaps check your max_input_time and max_execution_time settings. If you are uploading large files, it would stand to reason it would take a longer time.

Talinon left a reply on PHPUnit Returning 404 After First GET Request

@pedroroccon

Do you have multiple route files?

I remember having a similar problem, and I think it came down to having broken up my web routes into different files. This thread jogged my memory and I'm pretty sure was my problem:

https://laracasts.com/discuss/channels/testing/phpunit-says-route-not-defined

The thread topic says it throws a slightly different error, but that is because of using named routes. The underlying issue would be the same (404 in your case)

08 Aug
1 week ago

Talinon left a reply on ReflectionException (-1) Class Post Does Not Exist

@romainb

Sorry, I'm not sure why I was thinking PostController - rather, I meant Post.

I've looked over your code several times, and if you have done a composer dump-autoload like you said, there is nothing obvious that I can see that would cause this.

The only thing I can think of, going back to the container, is the possibility you have made a binding for your Post class that tries to resolve to something that can't be found. Like within AppServiceProvider doing something like:

$this->app->bind(\App\Post::class, 'SomethingThatDoesntExist');

That would certainly cause a ReflectionException when Laravel tries to resolve the Route Model Binding on the Edit/Destroy methods.

One way to test it is to fire up tinker and try:

resolve(App\Post::class); - which would return the ReflectionException

new App\Post; - would return a new model instance of Post

If that doesn't shed any light on the problem then I have no idea.. maybe another member can think of something.

Talinon left a reply on PHPUnit Returning 404 After First GET Request

@pedroroccon

I wonder why it is requesting app/organizacao instead of admin/organizacao?

1) Tests\Feature\OrganizacaoCrudTest::has_create_form()
Symfony\Component\HttpKernel\Exception\NotFoundHttpException: GET http://localhost/app/organizacao

Where is $this->sysPath coming from? That wasn't in your original code snippet.

Talinon left a reply on ReflectionException (-1) Class Post Does Not Exist

@romainb

Could you post the entire stacktrace?

This is a long shot - but by chance have you bound something into the container that has the same fully qualified namespace as your PostController?

06 Aug
1 week ago

Talinon left a reply on Checkbox Value

@hjortur17

Using Vue to represent the prices for the front-end is fine.

I also need the value to save to the database

Here is what I'm saying you need to consider:

When you submit the request to your back-end application, are you sending thru the price information to be stored in the database?

If so, what is stopping a user from manipulating the payload to the server? Instead of 50.00, the user submits 1.00

If your application doesn't consider this, it'll just heedlessly accepts whatever is submitted, and it'll persist 1.00 to the database.

What I'm suggesting is having your back-end check for the existence of the checkbox value, and if it's within the payload, then apply the price from your database when it goes to store the transaction. Don't let the front-end dictate what the end price will be.

Talinon left a reply on Passing Custom Variables To The Mail

@gouseferoz

No, it should not affect your email per se.

Although, Laravel serializes models for a reason. By not serializing, the queued job will only have the information that was available at the time the event was created.. which is fine in some cases.

But, if anything were to change on your models before the job is executed, it won't know about those changes.

Hopefully that makes sense?

Talinon left a reply on Passing Custom Variables To The Mail

It looks like all you really need as an additional dependency in your Mailable is the Issue model. Just pass both your User and Issue model from your controller:

IssueJob::dispatch($user, $issue)->delay(now()->addSeconds(1));

Then you can delete all those other lines from your controller and reference them from your template (as long as you make the $issue property a public property on your IssuesMail class.

For example:

<h2>Comment: <br> {{ $issue->comment }}</h2> 

It looks like you still might need to retrieve your question information from your Text model, but your Mailable can handle doing that; no need to have that in your controller.

Talinon left a reply on Passing Custom Variables To The Mail

@gouseferoz

I'm pretty sure what is happening is your User model is being serialized by the SerializesModels trait. In other words, it just stores your user's id in the job queue and then when the job is executed, retrieves a fresh instance from the database; hence why your temporary properties are lost.

Instead of adding temporary properties to your model (which I would argue is bad practice for Eloquent models in most cases) build an array, or another object, and pass that into your event along with your user.

Talinon left a reply on Passing Custom Variables To The Mail

@gouseferoz

My guess is that it is because you're trying to access your data in the template as an array instead of an object, which is how you set them within your controller.

<h2>Issue: {{ $user->question_issue }}</h2>

Talinon left a reply on Checkbox Value

@hjortur17

If you're dealing with money, I would suggest handling these prices in the back end. If the request contains the checkbox then apply the price from the database. Otherwise, what is stopping a dishonest user from just sending a post request with whatever price they feel like paying?

02 Aug
2 weeks ago

Talinon left a reply on Send Event To Pusher ( Laravel 5.7)

@atfinho

Did you restart your queue workers to update their memory for your application changes?

Talinon left a reply on How To Mock A Dependency Injection In Controller Test Isolation

@rfountain

You're not mocking your repository. You created a mock of your Server model. So, when you call Server::findOrFail()... within your repository, you're getting a new instance of Server, not your mock.

But - why do you even want to mock your repository? If you're testing if a server can be deleted, don't you want to actually assert that the deletion was made? By mocking, what are you actually testing here? According to your test, all you're really testing is that you get a 200 response, and that your repository returns true - but again, does that assert that it was actually deleted within the database?

Forgive me for making an assumption - but it looks like you just learned about the repository pattern and are trying to force it into a situation where it likely just isn't necessary. We've all been there - I remember trying to do the same thing. Have you considered just embracing how easy eloquent makes this without the over-complications of a repository? Do you ever foresee deleting a "Server" that isn't an Eloquent model? These are the questions you need to ask yourself.

Anyway.. just for learning purposes, if you wanted to make this test work, I think you'd need to bind your repository into the container, or bind an interface (which is often the case with repositories), so that you can swap it out with a mock when testing. Something like:

 /** @test * */
    public function it_deletes_a_server()
    {
    $this->mock = Mockery::mock(ServerRepository::class);
    $this->app->instance(ServerRepositoryInterface::class, $this->mock);

    $this->mock->shouldReceive('delete')->once()->andReturn('deleted');

    $this->call('delete', 'server/1');
    }

Then within your controller:

   public function destroy($serverId, ServerRepositoryInterface $repository)
    {
        $repository->delete($serverId);
    }

Laravel will automatically resolve your ServerRepository from the type-hint, as long as you have it bound into the container. Something like this within your AppServiceProvider:

$this->app->bind(ServerRepositoryInterface::class, ServerRepository::class);

However, you can see how complicated this gets where something as simple as below would likely do:

   public function destroy(Server $server)
    {
        $server->delete();
    }

Then your test could be:

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

    $server = factory(Server::class)->create();

        $response = $this->call('delete', "servers/{$server->id}")->assertStatus(200);

    $this->assertDatabaseMissing('servers', ['id' => $server->id]);
    }

Just giving you some things to think over and consider.

01 Aug
2 weeks ago

Talinon left a reply on How To Mock A Dependency Injection In Controller Test Isolation

@rfountain

I'm pretty sure this is what's happening:

public function delete($id)
    {
        return $this->model->find($id)->delete();
    }

You're calling find() before delete(), which is throwing the expected exception.

There are a few things you need to review:

You have a constructor for your repository that expects a model of Server - so how are you instantiating $repository within your controller without knowing the model?

You are route-model binding your Server model within your controller's destroy() method, which retrieves the model. You then pass the id into your repository, where you look up the model again by its id, then delete it.

If you want a pure repository, remove the type-hint from your controller and pass in the id of the Server model. Then let your repository be responsible for retrieving it by its id and then deleting it.

 public function destroy($serverId)
    {
        $this->repository->delete($serverId);
    }

But even then, within your respository, this doesn't make sense:

     return $this->model->find($id)->delete(); 

You're calling find() on a model that you already injected into the constructor (from somewhere?)

Maybe just do this instead:

 public function delete($id)
    {
        return Server::findOrFail($id)->delete();
    }

Then within your test, set up an expectation for both find() and delete() to both be called once.

Talinon left a reply on How To Mock A Dependency Injection In Controller Test Isolation

@rfountain

Laravel should mock the injection. It looks like you might need to mock your repository's method?

You're calling delete() on your repository, not the mocked Server object.

Does your repository instantiate a Server object and call delete on it?

Talinon left a reply on Fat(ish) Model That Creates A New Object. Expressive Or Bad Idea?

@ralphmrivera

I too will often extract logic like this into traits. I'll usually create a app/Models/Concerns folder to help organize the files (I always create a dedicated Models directory, but that's just a thing of mine)

So for your simple example above, I'd make a trait such as app/Models/Concerns/KnowsPaths.php

If I had a large complex app where "KnowsPaths" might be too ambiguous, I'd consider calling it something like KnowsUserPaths.

Imo, having a simple Use Concerns\KnowsPaths within the Model is nice and clean. You're coming to a compromise between both worlds where your model isn't creating objects, yet remains fat, but has an illusion of componentry.

I'm kind of curious about going with a service class, too. I'm always open to other ideas.

26 Jul
3 weeks ago

Talinon left a reply on Roadmap Help: Vue, VueRouter, Webpack, Laravel-mix, Vuex, Gulp, Sass

@payafterwork

It's a bit overwhelming at first.

If you're going to use webpack, you can drop gulp.

Mix is basically a configuration wrapper for webpack.

I wouldn't reach for vuex until you feel the need for it, which probably wouldn't be for awhile. So place that on last priority.

I would start off with this series to learn the basics of Vue:

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

Then you can graduate to the series that focuses on SPA:

https://laracasts.com/series/laravel-vue-and-spas

For Webpack & Mix:

https://laracasts.com/series/webpack-for-everyone

https://laracasts.com/series/learn-laravel-mix

I would worry too much about the 2 series above until you want to dive into those in more detail. The "Learning Vue2 Step by Step" covers the basics of webpack/mix enough to get you started.

25 Jul
3 weeks ago

Talinon left a reply on Suggestions On Test: A_logged_in_user_can_view_an_individual_job()

@trevorpan

Glad you got it figured out.. sorry about the factory typo - I'm accustomed to using a helper function to make it a bit more shorthand.

Talinon left a reply on Vapor - Taylor Otwell Presentation

@jlrdw

You asked recently why forum members single you out. This is why.

A 4 word post triggered you, once again, into typing long irrelevant rants that nobody cares about.

You are hijacking a thread with complete nonsense. Please stop.

Talinon left a reply on Creating Default Object From Empty Value

@vladimirc

I'm not sure why you're newing up a controller inside a controller. I think you need to consider creating a dedicated class to handle your calculations.

But anyway, to answer your question, just pass the data to your view at the end of your show() method.

There are many ways to pass data from your controller to a view. Here are a few examples:

return view('path.to.view')->with(['terms' => $paymentPlan->terms]);

// or

return view('path.to.view')->withTerms($paymentPlan->terms);

// or

$data['terms'] = $paymentPlan->terms;
return view('path.to.view')->with($data);


Then you can access it in your blade view via {{ $terms }}

24 Jul
3 weeks ago

Talinon left a reply on Creating Default Object From Empty Value

@vladimirc

Your problem first occurs here:

 $paymentPlan->$n->loanBal = $loanBalance;

You are trying to access a dynamic property name ($n) which doesn't exist on your $paymentPlan object. On your first iteration this will literally equate to $paymentPlan->0->loanBal

it's blowing up on 0->loanBal because 0 is not an object, and integers can't have properties.

Not exactly sure what you're trying to do here. Maybe you're trying to access a multidimensional array property within your $paymentPlan object that holds the term data? If so, you'd want to do something like:

 $paymentPlan->terms[$n]['loanBal'] = $loanBalance;

But that is just a wild guess..

Talinon left a reply on Suggestions On Test: A_logged_in_user_can_view_an_individual_job()

@trevorpan

Check your logs to see the cause of the 500 error.

I didn't pay much attention to it yesterday, but another problem you'll run into (if its not already the source of your error) is how you're handling the user_id within your factory. It should reference an actual user's id.

Change it like so:

...
'user_id' => function() { return factory(App\User::class)->id },
...

That way, it'll create a user within your database and return back its id.

Again, you can always override it with the make() or create() methods when you're using the factory. For example, within your test, if you would like $user to be the owner of the job, you can do this:

 $job = (factory(Job::class)->create([
    'deadline' => Carbon::now()->addWeeks(3),
    'user_id' => $user->id
 ]);

23 Jul
3 weeks ago

Talinon left a reply on Suggestions On Test: A_logged_in_user_can_view_an_individual_job()

@trevorpan

A factory will return an object.

You're getting that error because you're trying to access an object property on something that isn't an object - I suspect you've still assigned something to the $job variable other than what was returned from the factory.

Here, let me see if I can put you on the right path.. something like this might work:

First, make deadline a datetime datatype in your migration.


   public function a_logged_in_user_can_view_an_individual_job()
    {
        $this->withoutExceptionHandling();
        Event::fake();
        $user = (factory(User::class)->create());
        $job = (factory(Job::class)->create(['deadline' => Carbon::now()->addWeeks(3)]);

        $response = $this->be($user)->get('/jobs/'.$job->id);

        $response->assertStatus(200)
        ->assertSee($job->jobtitle)
        ->assertSee($job->formattedDeadline);
    }

Job Model:

 public function getFormattedDeadlineAttribute()
    {
        return $this->deadline->toDateTimeString();  // or however you want the date to be formatted
    }

JobFactory:

use Carbon\Carbon;

$factory->define(App\Job::class, function (Faker $faker) {
    return [
            'jobtitle' => $this->faker->sentence,
            'body' => $this->faker->paragraph,
            'deadline' => Carbon::now()->addWeeks(rand(1,5)),  // or override as I did above in create()
            'user_id' => $this->faker->numberBetween(1, 1000),
            'projectaddress' => $this->faker->streetAddress,
            'city' => $this->faker->city,
            'state' => $this->faker->state,
            'zipcode' => $this->faker->postcode,
            'biddertype' => $this->faker->word,
            'job' => $this->faker->word,
            'subjob' => $this->faker->word
    ];
});

Then in your view, use {{ $job->formattedDeadline }}

Talinon left a reply on Suggestions On Test: A_logged_in_user_can_view_an_individual_job()

@trevorpan

First of all, your job attributes are not getting stripped. You are assigning the temporary variable $job to the result of a string function toDateTimeString() of Carbon. If you dd($basejob) you'll see your attributes.

As for make vs create: make() generates a model within memory, where create() generates a model and stores it to the database. An example where make() comes in handy when you want to whip up a in-memory model to pass as parameters to a form post. Then you can assert that the model was persisted to the database via your application logic. As for your specific test above, you would want to use create(), otherwise when you test your get response your model won't exist in the database to be displayed on the page. If you were testing something like "a_job_can_be_persisted_to_the_database_upon_passing_validation" then using make() would be more appropriate.

UsingRefreshDatabase is likely fine, unless you have a specific reason not to use it. It will decide for you to run transactions or migrations, depeding on what database you're using.

Lastly - you might want to make some assertSee() calls to assert that the model is visible to the user:

$response->assertStatus(200)
    ->assertSee($basejob->jobtitle);  // for example
22 Jul
4 weeks ago

Talinon left a reply on Random Undefined Index: Driver Error

@movepixels

Do you have a 'cache' table created in your database?

If not, you can create it via: php artisan cache:table and then run a migration.

Just for testing, try changing the cache driver to 'file' and see if the problem goes away?

Do a php artistan config:clear after making the changes just to be safe.

Talinon left a reply on Random Undefined Index: Driver Error

@movepixels

Since your trace mentions CacheManager, I'm starting to think it has something to do with your cache configuration. Which might explain the randomness of the error.

Check config/cache.php for driver settings, and also check your env file for CACHE_DRIVER

Talinon left a reply on Random Undefined Index: Driver Error

@movepixels

What do you have set as your default connection?

Check near the top of your config/database.php file for the setting.


'default' => .....

Talinon left a reply on Random Undefined Index: Driver Error

@movepixels

The first step for a 500 error is check the logs for an error and follow the stack trace.

Talinon left a reply on The Requested URL /broadcasting/auth Was Not Found On This Server

@ankitsinghdalal

Have you enabled (uncommented) the BroadcastServiceProvider within your config/app.php?

   App\Providers\BroadcastServiceProvider::class,

Thankfully, Laravel makes it easy to define the routes to respond to channel authorization requests. In the BroadcastServiceProvider included with your Laravel application, you will see a call to the Broadcast::routes method. This method will register the /broadcasting/auth route to handle authorization requests:

19 Jul
1 month 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 month 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 every 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 month 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
1 month ago

Talinon left a reply on Get The Currently Active Queue Workers

@ronon

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
1 month 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.