rikh

rikh

Member Since 4 Years Ago

London

Technical Director at GatherContent

Experience Points 9,645
Experience Level 2

355 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 124
Lessons
Completed
Best Reply Awards 7
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.

12 Sep
2 years ago

rikh left a reply on Asynchronously Update A Model From A 'saved' Event

You could also test to see if relevant fields have changed before dispatching the job, using isDirty() and getDirty(). That way you only need to queue up the job if the address has changed. Changes to the lat / long fields can be ignored.

16 Aug
2 years ago

rikh left a reply on How Do I Limit The Time A User Can Access A Route/Page?

If 'select * from profile where id=1 is killing your DB, then you need to look at that. Only allowing 1 page view every 20 seconds seems like a very poor experience for anyone using your site.. :-)

If you really need to limit access to a section of your site, with no more than n visits in a given time period, then take a look at the Rate Limiting middleware that Laravel ships with. By default it is only applied to API endpoints, but you can add it to a given route, or group of routes if you want to limit access.

rikh left a reply on Route() Helper Not Returning The Expected Output

Probably route('auth.register.step.checkout', ['hash' => 'this_is_a_test_hash']);

You'll need to name the parameter, so it gets correctly mapped.

05 Feb
3 years ago

rikh left a reply on Eloquent Loop Through Array And Add To DB - Laravel/Eloquent

You'll need to set cart_item_id to the id of the CartItem model you created.

$cartItem - CartItem::create(blar);
foreach(modifiers blar) {
    // ...
    'cart_item_id' => $cartItem->id,
    // ...
}
19 Dec
3 years ago

rikh left a reply on Best Way To Backup MySQL Database From Laravel Forge Production Server?

Ideally you wouldn't be able to connect to your MySQL installation from anywhere on the internet - It will leave you open to all kinds of security issues.

Why not add your mysqldump script to forge, and have it execute on some regular schedule using cron. Once the data dump has been generated, have the script copy it somewhere safe, like an S3 bucket. The package @ohffs mentioned can do all of this, so it would be simple to add an artisan command to wrap everything up.

rikh left a reply on How To Handle Updating Email Using Validation

'unique' might get you what you want, if you specify the table and exceptions for the rule as well. One of the examples in the docs is a very close to what you are trying to do.

http://laravel.com/docs/5.1/validation#rule-unique

18 Dec
3 years ago

rikh left a reply on How To TDD/BDD By Mocking External APIs

I use AspectMock (https://github.com/Codeception/AspectMock) to mock out the API wrappers in my projects, so I can test all the possible error conditions from an external API as well as what happens when things are going well. For example...

        // Mock the stripe API
        $apiMock = test::double(StripeApiWrapper::class, [
            'createCustomer' => [
                'id' => 'TestStripeId',
                'subscription' => 'TestSubscription',
                'cardBrand' => 'VisaTest',
                'lastFour' => '1234',
            ]
        ]);

I can then perform a normal functional test in Laravel, and when it gets to calling Stripe, it will instead return that array and I can test that the users account has been updated to the correct state.

05 Sep
3 years ago

rikh left a reply on Model Factories Relations

@mstnorris @prodigy10 For those hitting this problem still, and looking for a solution, @devinfd PR has been merged into L5.1.16, so pull that and read the comments in https://github.com/laravel/framework/pull/9387 for details.

28 Aug
3 years ago

rikh left a reply on What's The Best Way To Send Response From Queued Job Class?

Since the actual completion state of the job won't be know for some time (basically, when your job reaches the front of the queue and is executed), there are only 2 ways for your front end code to find out the result. It can either poll the server, asking for the finished status every few seconds until the job is finally done, or better, use a broadcast event over websockets to inform the client of the finished result.

10 Aug
3 years ago

rikh left a reply on Testing File Uploads With PHPUnit

If you are using the Storage facade, then you can make use of the mocking features built into it to verify that the correct calls are made with the correct parameters.

http://laravel.com/docs/5.1/testing#mocking-facades

You can also mock Jobs and Events if needed...

http://laravel.com/docs/5.1/testing#mocking

If you want to really test that the file has really been uploaded to S3 or similar, then I'd make sure that things like the target bucket are configured in the environment, so you can send stuff to a test bucket in testing. You'd then have to just try and download your test file after the upload completes and ensure that it has the correct content. This will be slow though, so possibly put it in a separate set of tests that you don't have to run 500 times a day.

09 Aug
3 years ago

rikh left a reply on PHPStorm 9 Not Showing Syntax Highlighting For Certain File Names

If you manually created the file, it is possible that PHPStorm guessed the file type incorrectly at the start and has now remembered that.

Look in the preferences under File Types and see if your filename is listed under some odd filetype. Delete the bogus entry.

24 Jul
3 years ago

rikh left a reply on I Have A Question About Db Read/write

Sorry - don't know. However, if you dig into the source code, it might offer clues as to how you should reset the connections afterwards.

rikh left a reply on I Have A Question About Db Read/write

There is this function....

http://laravel.com/api/5.1/Illuminate/Database/Connection.html#method_selectFromWriteConnection

Which allows you to make a select from a write connection. Might be somewhere to start investigating...

rikh left a reply on I Have A Question About Db Read/write

It's common to have separate read and write databases at scale. All the writes go to the master DB and all the reads go to the replicated slaves.

So, to answer a few peoples questions about why and how would it work, mysql will replicate data written to the master db, so when a read comes along that hits the read slave, it already has the data.

However, the original question was once he makes a read request to the write DB, all future reads and write end up going to the 'write' connection, instead of the normal split. How do you reset the connection so it goes back to all writes hitting the write DB and all the reads going to the read DB.

I'm not sure that Laravel provides any built in support for managing which connection your queries are sent to, and you are expected to use the appropriate connection manually yourself.

23 Jul
3 years ago

rikh left a reply on Best Method For One-time Scheduled Task

Or you could push the whole problem out of your app and into a service that does this kind of thing, like Drip. https://www.getdrip.com/

(never used them, so don't know if it would be suitable)

21 Jul
3 years ago

rikh left a reply on Regular Expression To My Password

Your regular expression will only match a single character

Try this instead

'password' => 'required|confirmed|min:6|regex:/^[a-zA-Z0-9!$#%]+$/',

Though this will also limit you to only the characters in your list - no other characters will be allowed.

Also, when using the regex validator, it is often good practice to use the array format for the rules, so you don't get any accidental parsing errors.

02 Jul
3 years ago

rikh started a new conversation Setting Up The Job Pipeline In The Dispatcher In L5.1

Now that the BusServiceProvider has moved into the framework, what is the recommended way of added classes to the Bus pipeline?

I'm trying to add something to the pipeline that will wrap job handlers in a DB Transaction. Any suggestions as to how to do this now.

19 Jun
3 years ago

rikh left a reply on Problems Testing Form Validation Errors In L5.1

OK, I've figured out what was going wrong...

My form library was created by the IOC the first time it was used. This happened inside the first call to visit().

The call to submitForm() in the test then started a second http request, but my form library was still hanging around in the IOC, so the same one was used for the second request. The form library had the request injected into it's ctor, so when it looked to see if there were errors in the session, it was using the session object from the first request.

I've struggled to find a clean way to ensure my object was destroyed at the end of the request and recreated at the start of the new request (suggestions appreciated), so I've changed it to be passed an instance of the app and fetch the session from that each time I need it. End result: I get the current session and everything works fine.

rikh started a new conversation Debug Phpunit Test Using PHPStorm And Homestead

I use homestead as my VM and normally ssh in and run PHPUnit.

I also use PHPStorm and use the debugger to track down problems.

However, I've only been able to get this to work when debugging the site from the browser. I've never been able to get PHPStorm to start a debug session when running something on the command line in the VM.

I've got PHPStorm 9 at the moment and have set it up to run the tests on the VM and that is working fine. The Debug Tests also appears to work and runs the tests, but the code never hits any of my breakpoints.

Firstly, has anyone managed to debug PHPUnit tests, running on homestead, using PHPStorm? If so, what is the magic needed to make it work?

rikh left a reply on Problems Testing Form Validation Errors In L5.1

My form library (that generates the markup for the forms, including any error messages) fetches the error data from the session like so...

// get the errors in the ctor
$this->errors = $this->request->session()->get('errors', new MessageBag);

// later, when rendering an input control, fetch an error message relating to it...
$error = $this->errors->first($fieldName);

rikh started a new conversation Problems Testing Form Validation Errors In L5.1

I am using the new testing framework in 5.1 and trying to test that a form displays the correct validation errors if you attempt to submit it with something wrong (eg a missing required field).

The test looks a little like this...

    $this
        ->visit('/example')
        ->see('Example Title')
        ->submitForm('Do Something', [
            'from' => $from,
            'to' => $to,
            'note' => $note,
        ])
        ->onPage('/example');

    // This test works fine
    $this->assertSessionHasErrors(['to' => 'Some error message']);

    // this test fails
    $this->see('Some error message');

So the test framework can see the errors returned in the session, but my views see no errors in the session, so they don't display any error messages on the page. They do see the old input values though, so the session is at least partially working.

I can manually test feature this by visiting the page, submitting the form and seeing the error messages, so I am happy that the code works. I just need my tests to be able to show that.

@JeffreyWay This all used to work perfectly when I was using Integrated on 5.0.

11 Jun
3 years ago

rikh left a reply on Lists Method Error With Orm Relationship

you'll need to specify the table name as well. I expect the error is happening, as a join is being used between the 2 tables, and they both have an id field.

$this->writer->books()->lists('books.name', 'books.id');
10 Jun
3 years ago

rikh left a reply on Upgrading From Laracasts/integrated To Laravel 5.1 Native Tests

It looks like Model Factories in L5.1 don't support the ability to create dependencies.

With TestDummy it was possible to define elements of a model by referencing another model factory (for example 'company_id' => 'factory:App\Models\Company'

Can you still use TestDummy in L5.1, as this seems like a major omission.

rikh left a reply on Upgrading From Laracasts/integrated To Laravel 5.1 Native Tests

@olimorris I had already tried deleting the vendor folder and rebuilding it from scratch. No joy sadly.

rikh left a reply on Upgrading From Laracasts/integrated To Laravel 5.1 Native Tests

However, I am still having trouble.

It is looking rather like my @before function in my TestCase class are not being called, which means my database does not have any migrations or seeding run on it before the tests.

Any ideas what I might have missed that's caused this to break?

rikh left a reply on Upgrading From Laracasts/integrated To Laravel 5.1 Native Tests

Last night I tracked down the source of the massive slowdown.

In a frenzy of cut and paste, I had converted a couple of old TestDummy object creations from this:

$user = Factory::create('App\Models\User', ['manager_id' => $manager->id, 'company_id' => $manager->company_id]);

to

$user = factory('App\Models\User', ['manager_id' => $manager->id, 'company_id' => $manager->company_id])->make();

The correct format should have been

$user = factory('App\Models\User')->make(['manager_id' => $manager->id, 'company_id' => $manager->company_id]);

09 Jun
3 years ago

rikh started a new conversation Upgrading From Laracasts/integrated To Laravel 5.1 Native Tests

I had been using Integrated and TestDummy in my L5.0 project. I've just upgraded to 5.1, which includes all the awesome of Integrated and TestDummy out of the box.

I've updated all my TestDummy definitions and that seems to have worked well and I'm working though my tests.

However, PHPUnit has started to run REALLY slowly now. I'm talking minutes before even the first test runs. I've rebooted my VM and run composer update a few times, but I have no idea why it's going so slow. (top says 100% CPU being used by PHP)

@JeffreyWay, is there an upgrade guide?

Anyone got any suggestions as to what might be messing with PHPUnit performance.

rikh left a reply on What Am I Missing?

You've probably not updated you /etc/hosts file to set up the domain http://myproject.dev to point at your VM.

21 May
3 years ago

rikh left a reply on Post Request Not Working.

By default, any POST request must include a valid CSRF token with it. This is intended to protect form submissions.

Your API isn't a form, and the CSRF token isn't appropriate, so simply disable this feature in your app. It is controlled by a middleware class (in Laravel 5) that ensures the token is present and correct for all POST requests. As others have pointed out, the list of middleware that will be used on each request is defined in app/http/Kernel.php. Find the line at add the CSRF middleware to the list and comment it out.

18 May
3 years ago

rikh left a reply on Count From SubQuery

I don't think that is the correct way to use with().

with() is intended for eager loading related models. You can filter the set of related models returned using a closure similar to what you have. However, I'm not sure that the count() call you have in the filter will be doing what you think.

The count() is not returned here, so will simply be discarded - the closure is really just an opportunity to modify the query that Laravel will use to select the related models.

Also, do you have a relationship defined in your Shop model called shop_coupons?

16 May
3 years ago

rikh left a reply on Set Langfiles Data As Model Variable?

You'd had to do that in a constructor - PHP does not allow you to set default values of class variables using function calls.

rikh left a reply on Add Queue From Controller

Trying using the contract instead - replace your use statement with this...

use Illuminate\Contracts\Queue\Queue;

rikh left a reply on Redirect With Input To External Link

with() adds the values to the session, which if you are redirecting off to a different server at a different domain, won't be available at the destination.

You'll need to pass the values as parameters or in the query string.

I expect there is a neater way of doing it, but something like...

$queryString = http_build_query($arguments);
return \Redirect::away('https://example.com/process/?'.$queryString);

rikh left a reply on Class Log Does Not Exist

I have a similar problem. My tests all work fine on Vagrant, but when they are run on Scrutinizer as part of a pull request, they fail because they can't find Log::info();

rikh left a reply on Can't Drop Composite Primary Key Via Migrations

Have you tried doing this as 2 separate statements?

DB::unprepared('ALTER TABLE `votes` DROP PRIMARY KEY');
DB::unprepared('ALTER TABLE `votes` ADD PRIMARY KEY (`id`)');
15 May
3 years ago

rikh left a reply on Where To Start Learning Laravel 5?

Here!

Laracasts has to the best possible resource for this.

14 May
3 years ago

rikh left a reply on Deploying A L5 Application

About as simple as you can hope for. Copy your code onto the server, composer install and create a .env file, point your web root at the public folder.

Solutions like Forge (https://forge.laravel.com/) and Envoyer (https://envoyer.io/) make it even simpler.

rikh left a reply on Snake_case Or CamelCase

Whichever one you like the most.

rikh left a reply on Receiving Different Fields On An "API" From Multiple Companies

You can use the 'after' feature of the validation to remap all the fields into a standard set of fields that your repository can cope with.

rikh left a reply on Designing Restful Api

Some great references to look at when you're thinking about building an API....

http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api https://leanpub.com/build-apis-you-wont-hate

This is also a great package to help with building APIs http://fractal.thephpleague.com/

13 May
3 years ago

rikh left a reply on Designing Restful Api

I'd have a resource for each type of data. One to get the nav data, one for the user etc. They are all separate resources.

If you design your API right, you'll be able to request multiple things in a single request, if performance is a concern.

rikh left a reply on Eager Loading And PHP (not MYSQL) Performance Issue

If you can't identify exactly where the performance hit is coming from, then I would suggest stepping through the code in the debugger. When you hit a step that is taking a long time to complete, run it again and step into that function until you zero on the thing that is actually taking all your time.

If you have a profiler, this will do the hard work for you and identify exactly where all your performance is going. It is often something silly that is easy to avoid :-)

11 May
3 years ago

rikh left a reply on Laravel 5 Commands

For simple things, I tend to leave the logic in the controller.

When it gets more complicated, like in your example, I prefer to dispatch a command to do the work.

I'll also often fire events at the end of the command handling, which allows me to create listeners to those events to perform additional tasks. For example, most of my event listeners that I use to send emails end up dispatching another command to send the email. These email commands are queued, so they don't slow down the request.

It keeps everything separate, the commands means the actions can be reused (eg in artisan commands) and it becomes simpler to write tests for them.

28 Apr
3 years ago

rikh left a reply on Writing Functional Tests That Validate If An Email Got Sent

OK, I've solved this by adding a new Mail Transport to Laravel last night that just collects all email sent and makes them accessible in the tests.

I'll try and bundle it up into a package one day, as it seems really useful. Now I can do stuff like...

$this->assertEquals(1, $mail->getMessageCount());
$messages = $mail->getMessages();
$this->assertEquals('My Subject', $messages[0]->getSubject());
27 Apr
3 years ago

rikh started a new conversation Writing Functional Tests That Validate If An Email Got Sent

I have a form that users can submit. One of the many things that happen when the form is submitted is that an email gets sent using Laravel's normal email features.

How do I write a functional test for the feature that is able to check that the email is sent and appears to have the correct content.

I found an example using Symfony, which also uses swiftMailer under the hood here... http://symfony.com/doc/current/cookbook/email/testing.html

Can someone suggest a way to do this using Laracasts Integrated or CodeCeption.

22 Apr
4 years ago

rikh left a reply on Redirect::route(...) Adds :80 To URL Causes Error.

Is this an https site? Is it behind a load balancer? Is the load balancer dealing with SSL and forwarding http requests on to your site? If so, you probably need to set some trusted proxies, so your site know it originated from an https request.

An excellent package for dealing with this out of the box is Chris Fidao's excellent Trusted Proxies https://github.com/fideloper/TrustedProxy

rikh left a reply on Server Size For 30K Daily Pageviews

The truth is that none of us will be able to tell you what server you need to deploy to run an app we know nothing about. If you calculate the answer to life, the universe, and everything on every request, you'll be needing something more powerful than a site that returns "OK" for every request, regardless of how many visitors you get.

Don't forget that you don't have to get it 100% correct first time. Choose the server that you think should be capable of delivering the traffic levels you are expecting.

If you turn out to be wrong, and it's running a little slow, redeploy on something bigger / more powerful. If it is critical that you can serve traffic fast, then overestimate and put in something much bigger than you think you'll need. You can always downscale later to something smaller / cheaper if you were way off.

You could also deploy to your best guess, then run your own load tests yourself before 'going live' to make sure your estimates are right.

29 Mar
4 years ago

rikh left a reply on What Is The Meaning Of The N + 1 Problem?

It's the problem caused when you need to make N + 1 SQL Queries, where N is the number of items.

For example, lets say you have a table of Blog posts, called posts. You can fetch all the posts in 1 SQL query (eg SELECT * FROM posts). Lets say this returns 100 rows of data. Now, for each post, you want to find the author of the post, so you might choose to loop over all the posts you got back from the first query and make a separate SQL query for each one (eg SELECT * FROM users WHERE user_id = ?). You'd end up making 100 queries to get the authors, plus 1 query to get the posts.

Obviously my example above could be trivially solved with a join, fetching both bits of data at the same time and making the overall query much more efficient.

When you are using an ORM like Eloquent, it can sometimes be easy to create code that produces the a result similar to the above example though, as it isn't always obvious what queries will be made when. If you are aware of the problem and understand how the ORM is working, it can makes it simpler to avoid the problem in the first place. Eloquent has a feature called Eager Loading (see link from @Mo7sin) that reduces this problem down to something more manageable.

26 Mar
4 years ago

rikh left a reply on Queue Worker

I'm not clear how to work with supervisor during a deployment. When we deploy a new release it ends up in a new folder linked to with a symlink (same way Envoyer works), so I need to stop the queue worker before the deployment and then restart it again after the deployment completes, using the new version of the code.

Any ideas how to stop the worker during the deployment process, without supervisor jumping in and restarting it automatically?