D9705996

MaaS Technical Lead at Sabio Ltd

Experience

75,440

6 Best Reply Awards

  • Member Since 3 Years Ago
  • 742 Lessons Completed
  • 1 Favorite

20th September, 2018

D9705996 left a reply on QueryException - SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row: A Foreign Key Constraint Fails • 12 hours ago

I would also suggest looking at https://laravel.com/docs/5.7/validation as you could hugely simplify your code by using a FormRequest to validate your request data.

Run `php artisan make:request ProductImageRequest, amend the validation rules to make your use case then you can change all of you code to

public function addProductImage(ProductImageRequest $request){

  $commRepo = new CommonRepository();
  $image = $commRepo->uploadBase64File($request->image,'product_images','ProductImage');

  $product = new Product($request);
  $product->image = image['file_name'];
  $product->save()

}

Not only does this reduce the complexity but you will ensure that the Request data is valid and prevent issues with foreign key constraints.

D9705996 left a reply on QueryException - SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row: A Foreign Key Constraint Fails • 12 hours ago

The order of the columns in your error message you have posted look wrong.

It looks like

 price = 6
 product_category_id =11.11

The argument order is mismatched between

public function addProductImage($base64Text,$name,$description,$product_category_id,$price)

And when you call the function

$result = $this->productRepo->addProductImage($base64String,$name,$description,$price,$product_category_id);

Swap the variables in one of the above.

D9705996 left a reply on Should Caching Be Done Within A Repository? • 13 hours ago

I'm not sure on best practice but laravel links posted this tutorial that uses caching in a repository.

https://www.youtube.com/watch?v=34zQR21MIoU

The content seemed reasonable to me

19th September, 2018

D9705996 left a reply on Laravel : Pusher Listen For Private Channel With Unique Id • 1 day ago

If you haven't already watch this series on laracasts. It's not all free but the paid are worth the $15/month subscription IMO

D9705996 left a reply on Laravel : Pusher Listen For Private Channel With Unique Id • 1 day ago

$this->activity->post_id

Where does activity come from as you are passing a comment variable to the event. Is activity a public property on the FeedCommentActivity class.

It might be helpful to update the question with full event class so we have a full picture

D9705996 left a reply on External Broken Link Checker • 1 day ago

If your looking for an open source library the same team have released this library that you can use in your own laravel applications

D9705996 left a reply on External Broken Link Checker • 1 day ago

You should check out Oh dear! the wonderful @freekmurze and @mattiasgeniar.

It can detect and alert on dead links amongst other really useful functions

D9705996 left a reply on Changing The Default "subject" Field For The Verification Email In Laravel 5.7 • 1 day ago

Alternatively if you need more control override the sendEmailVerificationNotification function on your user model

    public function sendEmailVerificationNotification()
    {
        $this->notify(new Notifications\VerifyEmail); // Replace this with your custom notification class
    }

Details on creating notifications are in the official docs (https://laravel.com/docs/5.6/notifications#mail-notifications)

D9705996 left a reply on Changing The Default "subject" Field For The Verification Email In Laravel 5.7 • 1 day ago

You need to add a translation string to your language specific json file e.g resources/lang/en.js with

{ "Verify Email Address": "My Special Subject" }

This key is also used for the action button text so you might want to look at the source to see what will change. I don't recommend changing this file as it's part of the core framework.

D9705996 left a reply on Dynamic Input Field Field Disable • 1 day ago

Without seeing your code it's hard to give concrete advice but I assume your using v-forto loop round the inputs.

If you pass a second argument to v-for it will give you the index of the input

  <input v-for="(item, index) in items" ...></input>

You can then bind the disabled property on the input to be true if the index isn't the size of items

<input :disabled="index !== (index.length - 1)" ...></input>

D9705996 left a reply on Pros And Cons Of Laravel Dusk Vs. Ghostinspector.com • 1 day ago

Cost is a fairly universal decision factor. Dusk is free but even though most services have a free tier the generally have limitations.

A con for dusk is it can be complex to setup and configure outside of valet and homestead. I'm in the middle of trying to get dusk to work within my continuous integration setup on dockerwith very limited success!

D9705996 left a reply on Obtain Specific Attributes From Collection • 1 day ago

You could use pluck to map your id's to names with

  $products->pluck('name','id')->all();

D9705996 left a reply on Is VUE JS Protected Against Changing Price Values In Webshop? • 1 day ago

Thanks. Helps others looking for "answers"

D9705996 left a reply on Is VUE JS Protected Against Changing Price Values In Webshop? • 1 day ago

@andreasbakir - if this answers you question can you please mark as solved.

D9705996 left a reply on Is VUE JS Protected Against Changing Price Values In Webshop? • 1 day ago

You should always perform server side validation when a user submits data to your server rather than relying on client side validation.

That way if a user does change something in your Vue/JavaScript code such as the price you can either reject the Request or use the data in the back end when the User submits their request to the backend.

Always mistrust any data being submitted from the front end in the backend until it has been validated.

17th September, 2018

D9705996 left a reply on Laravel Best Practise For Running Multiple Queue Jobs • 3 days ago

You can certainly dispatch jobs in another jobs handler method.

However you may want to look at job chaining.

This allows you to run your jobs in order and will stop if a step fails e.g.

JobA::withChain([
    new JobB,
    new JobC
])->dispatch();

D9705996 left a reply on How To Allow Admin User To Simulate Or Authenticate As Any Other User On My Site? • 3 days ago

@Cronix - I agree with you completely that an admin/superuser should be able to edit other users resources but there are valid use cases for user impersonation by an admin... I.e. troubleshooting/replicating issues as the User

If anyone is looking for a package for user impersonation then https://github.com/404labfr/laravel-impersonate is an excellent choice but remember to be very careful to prevent unauthorised access to the routes!

D9705996 left a reply on How Can I Block The Guard When Registering A User • 3 days ago

You should check out https://laravel.com/docs/5.7/verification.

This gives you what you want out off the box. There is a free video for that here

https://laracasts.com/series/whats-new-in-laravel-5-7/episodes/1

D9705996 left a reply on Prevent Login Before Email Verification • 3 days ago

When you set up the email verification routes it adds a couple of routes but this one

$this->get('email/verify', 'Auth\[email protected]')->name('verification.notice');

You could replace this with your own route that does something like

return redirect('login')->withErrors([
  'message' => 'you must verify your email first.'
]);

D9705996 left a reply on Unable To Send Email From A Laravel Command • 3 days ago

Everything looks ok in you code as far as I can see. What sesusion driver are you using?

Do you have StartSession setup in your middleware groups as per this. If you run php artisan route:list do you see your routes or an error?

D9705996 left a reply on Unable To Send Email From A Laravel Command • 3 days ago

Can you share the contents of your emails.notify view.

14th September, 2018

D9705996 left a reply on Datebase Design • 6 days ago

The best practice would tiny integer columns for each Boolean value.

However if you really wanted to store the values in one column you could use an integer column with bit mask operators as described here

Personally I would go for multiple columns in a table everytime

D9705996 left a reply on UpdateOrCreate Summing Previous Column Value • 6 days ago

You could use a model observer to hook into the updated event and increment the price there

public function updated(Flight::class $flight) {
  $flight->increment('price, 12):
}

Just make sure you register the observer in the boot method of App::Flight. You can of course do this all in the Flight class boot method but I prefer using observers to keep the logic separate.

I would question why you want to do this though as if you update anything related to the Flight like the name you would increment the price.

I would add a new method to the Flight class like

public function incrementPrice($price) {
  $this->increment('price, $price);
}

Then call this method only when you need to update the Flight price. This allows you to add any specific validation, such as a flight price can't be more than 2000). You also interchange trip and flight in the question but with the same schema and data so I assume they are the same thing.

13th September, 2018

D9705996 left a reply on Resend Password Confirmation • 1 week ago

When you run php artisan make:auththere will be a verify.blade.php file in your views folder built from this template.

You can change this however you want and if an unverified user tries to access a route that needs verification they will see this page

12th September, 2018

D9705996 left a reply on In Memory Database Leads To The Table Is Empty. • 1 week ago

What are the contents of the whoops page (You should also be able to get the error from storage/logs/Laravel.log)

I'm wondering if it might be something like a missing APP_KEY but error message will help determine

D9705996 left a reply on Passport Password Grant Tokens • 1 week ago

Previous comment was related to storing your unique business logic that specifies how the request data is populated within the middle-ware rather than a definitive method.

This is the reason you cannot find a package/tutorial that will give you some general code to use as everyone's use cases will be different.

11th September, 2018

D9705996 left a reply on Passport Password Grant Tokens • 1 week ago

My advice would be to create a before middleware that takes the Request parameters that you are happy to pass from the client application and merges with an array of the parameters you do not want to expose e.g. client_id and client_secret.

I would generate a new client_id and secret and hardcode these in the middleware and test if you can then post to the oauth/token route with just the username, password and grant_type ( you will need to add your middleware to this route only)

Assuming this works you can extend to fit your own use case, e.g. create a new client when user registers and associate with the Users model. Then in the middleware you can find the users specific id and secret in the database and replace the hardcoded values.

I am not sure this is best practice but meets your goal of hiding the client_* keys in the backend

D9705996 left a reply on Passport Password Grant Tokens • 1 week ago

You can use a proxy class to hide the client ID and secret. http://esbenp.github.io/2017/03/19/modern-rest-api-laravel-part-4/ has an example. It's quite full on but should help you get on track

30th August, 2018

D9705996 left a reply on Long Running Job (Hours Long) • 3 weeks ago

If you are using redis/horizon you can set the retry_after and timeout options as per

https://github.com/laravel/horizon/issues/255#issuecomment-349621321

23rd August, 2018

D9705996 left a reply on Should I Cache Large Datasets In Redis? • 4 weeks ago

I would only reach for caching when you find you actually need it I.e. your application feels slow. Laravel makes it really easy to cache eloquent queries with minimal code changes so don't worry about it. Also remember caching has down sides like cache invalidation

9th April, 2018

D9705996 left a reply on Use A Different Database For A Single Test? • 5 months ago

@jlrdw - Prefect Thank you. I added DB::connection('mysql'); at the top of the affected test.

6th April, 2018

D9705996 started a new conversation Use A Different Database For A Single Test? • 5 months ago

I have the following test setup that tries to add an entry to a model and when I run the following test with the sqlite in-memory database everything passes.

        $this->json('POST', 'api/v1/authentications/ssh/credentials', [
            'username' => 'root',
            'password' => 'goofFnBfo9mi0Y',
            'description' => 'test'
        ])->assertStatus(Response::HTTP_CREATED);

However when I try to replicate the test with the production API I get a "Data too long for column" error from MySQL because the password value is being encrypted and is longer that the 191 character limit on the field.

I am going to change the column type to fix the problem but I really want to fix the test.

Is it possible to configure this single test to override the default database to use a MySQL database?

9th March, 2018

D9705996 left a reply on Best Practice To Store Decimal Values In Database • 6 months ago

This has good example of how to deal with currency and underlines @martinbean comments

17th February, 2018

D9705996 left a reply on How Can I Solve "Connection Could Not Be Established With Host Smtp.gmail.com"? • 7 months ago

@moses - do you have access to the command line on your staging server? If so you can try

telnet smtp.gmail.com 587

If you don't get a connection refused error then the issue is not network related

16th February, 2018

D9705996 left a reply on End To End Testing Of A Network Service • 7 months ago

I will do but I had to revert the changes as I need approval to install the PECL RPM in my work CI estate and didn't commit the changes locally :(

15th February, 2018

D9705996 left a reply on End To End Testing Of A Network Service • 7 months ago

@Borisu - I tried this out and it worked. I replaced the while loop true value in the example with a carbon instance in the future and checked if now was greater and if so end.

14th February, 2018

D9705996 left a reply on Vue-test-utils And Vuex • 7 months ago

I have managed to find a solution to the problem and to be frank it is clearly documented so a complete misunderstanding issue.

import Vuex from 'vuex';
import vuexstore from '../../../resources/assets/js/store.js'

describe('Navigation Toggler', () => {

  let wrapper;
  let store;

  const localVue = createLocalVue();

  localVue.use(Vuex);

  beforeEach(() => {
    store = new Vuex.Store(vuexstore);
    wrapper = mount(NavigationToggler, { store, localVue })
  });

...

The above sets up a local Vue instance with access to the store and uses this to create the wrapper.

Not sure if it is regarded as best practice but I will mark as the correct solution

D9705996 left a reply on End To End Testing Of A Network Service • 7 months ago

@borisu - Very interesting. I was aware of inotify but didn't realise there was a PHP implementation. I will try this out and if it works and doesn't make the tests too complex I will award you the deserved credit :D

13th February, 2018

D9705996 started a new conversation End To End Testing Of A Network Service • 7 months ago

I have an endpoint that accepts JSON data and fires an event to push that via UDP to a local network service (A graphite time series database)

In all but one of my tests that interact with the backend I am faking the event class and ensuring that the correct events are being fired (there is business logic involved to determine what parts of the JSON should be stored)

This is almost perfect but to catch any problems when I upgrade the backend (and to let me sleep easier at night as this score to the application), I have one test that fires one event and then checks to see if the corresponding file appears in the local file system.

As there is a short delay between the event being handled and the backend creating the file I have had to add a half second sleep to the test. It works but seems wrong. I thought about a loop to repeatedly check for the file and fail after X seconds but seems equally wrong.

I wonder if anyone else has had similar experience and found anything more elegant.

D9705996 left a reply on Once Again, Polymorphic Many To Many? • 7 months ago

As a report job can only be of a single type you don't need a many to many relationship.

A polymorphic relationship will suffice.

You just need to ensure that when report job is created you specify the correct Id and type are inserted into the morph fields and to you can then access the eloquent relationship as per a non-polymorphic version

D9705996 left a reply on Query Sqlite Database While Test Is Running. • 7 months ago

It looks like this is not possible.

It would not be normal to interrogate the database directly with SQL mid test. Is their a reason you cannot do dd the all the models records in your test

e.g. dd(User::all());

D9705996 left a reply on Vue-test-utils And Vuex • 7 months ago

@syropian - what you seems to make sense to me to certain extent but I am trying to follow the testing vue series mantra of test the "public" api of the component. E.g. I only care that when the component is clicked the icon the user sees changes (there are other things that occur in the UI at a variety of levels in the hierarchy).

To avoid having to emit and listen to events all of the application I feel Vuex is the correct solution and has created some pretty elegant structured code.

Do you have any examples or suggestions about "a different test" might look like that doesn't involve duplicating the logic from the store (I briefly toyed with this idea but in the words of Jeff it had a high ick factor)

D9705996 started a new conversation Vue-test-utils And Vuex • 7 months ago

I am working on a my first larger application with Laravel and Vue and I am trying to figure out how to integrate Vuex into vue-test-utils using mocha-webpack and expect. Below is a simplified view of the store

{
    "ui": {
        "navigation": {
            "toggled":false
        }
    }
}

I have an mutation that toggles the toggled boolean value which is commited when the user clicks a button.

Everything works as expected in the browser but when I try to run the following in a test

  it('should toggle', () => {
    wrapper = mount(NavigationToggler); 
    wrapper.find('ul').trigger('click');
    expect(wrapper.find('svg').attributes()['data-icon']).toBe('chevron-circle-right');

    wrapper.find('ul').trigger('click');
    expect(wrapper.find('svg').attributes()['data-icon']).toBe('chevron-circle-left');
  })

I am getting the following error

       "before each" hook for "should have the correct positioning":
     TypeError: Cannot read property 'state' of undefined

I am pretty sure it is because the mounted component doesn't have access have access to the Vuex store but looking through the documentation I have become a little lost as the documentation is talking about mocking the store using createLocalVue but I think this is testing that specific mutations, actions, etc are being fired but I am trying to blackbox test the full thing.

Any pointers gratefully accepted

10th February, 2018

D9705996 left a reply on Passport Working On One Dev Machine But Not The Other • 7 months ago

Ah ok, I know with apache you have to configure it to accept the authorization header but not relevant to you.

Any additional information in any logs?

9th February, 2018

D9705996 left a reply on Passport Working On One Dev Machine But Not The Other • 7 months ago

What webserver are you using? Is it apache?

6th February, 2018

D9705996 left a reply on Taylor Otwell Cancelled My Account Without Asking Me • 7 months ago

@georgek - this doesn't seem to be your first issue with forge. Regardless of interpretation of the t&c's for forge it does look like a sensible outcome. You now have a provider you are happy with and Taylor can continue to support the many customers using this service successfully. I'm sure if you need support in the future and if you abide by the laracasts code of conduct you will receive the full support of all of its members

19th January, 2018

D9705996 left a reply on Git Workflow Question • 8 months ago

Gitlab is super easy to install, update and maintain. It also has advanced features like continuous integration that you can use if/when you need them. I will warn that git is complex but worth it compared with svn, etc.

https://laracasts.com/series/git-me-some-version-control will get you through it.

If you need any gitlab help please let me know.

17th July, 2017

D9705996 left a reply on Delay Execution Of An Event Listener By A Specific Time • 1 year ago

Without seeing your code it's hard to tell exactly how you plan to achieve you goal but sounds ok. What I would do though is in the controller create the model as normal without performing the thumbnail creation and then fire an event from the controller that performs the isolated image optimisation (You can pass the model into the event constructor)

16th July, 2017

D9705996 left a reply on Delay Execution Of An Event Listener By A Specific Time • 1 year ago

https://laravel.com/docs/5.4/events#dispatching-events

You for firing an instance of your event class

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.