mikenewbuild

mikenewbuild

Member Since 2 Years Ago

Manchester

Owner at Newbuild Studio

Experience Points 56,990
Experience Level 12

3,010 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 509
Lessons
Completed
Best Reply Awards 10
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.

16 Aug
3 days ago

mikenewbuild left a reply on Clean Code

Without using any other techniques, you can extract the logic that you repeat, and store the variances in an array.

$paths = ['file_path1','file_path2','file_path3'];

foreach ($paths as $path) {
    if ($request->hasfile($path)) { 
        $project->{$path} = $request->{$path}->store(); 
    }
}
08 Aug
1 week ago

mikenewbuild left a reply on Integrate Different Sources Of Notifications

Well, working back from that integrations would need to return a collection of instances with notify methods that accept a payload, and already have enough details do their thing.

So first of all I would try to figure out if / how to aggregate all those integration types and have them conform to that contract.

It sounds like maybe all of these integration types are too distinct to be solved simply by a polymorphic relationship. But it could be solved by polymorphism in the stricter sense, whereby you have factory methods to return the correct model instances, that way the data you store for each can be independent so your Stream model would have direct relationships to webhook_integrations, email_integrations etc. and integrations is a convenient aggregator for them.

Again, wildly hypothetical!

mikenewbuild left a reply on How To Output A Json Array And Loop Through Variables

👍

You don't need to do any json conversion when you'r in blade/PHP land. You constructed a nested array in your Controller, and passed it down to the blade file, where you can iterate over it.

The fact that you later convert it to json for the response is because that's a format that javascript and other languages can parse.

mikenewbuild left a reply on How To Output A Json Array And Loop Through Variables

Okay so get rid of the json_encode stuff and do:

@foreach ($guests as $guest)
{{ $guest['guest_name'] }} | {{ $guest['gluten'] }}
@endforeach

mikenewbuild left a reply on How To Output A Json Array And Loop Through Variables

Maybe also try $item['guest_name'] rather than $item->guest_name if this is an array you've built up yourself, rather than an array of objects.

mikenewbuild left a reply on How To Output A Json Array And Loop Through Variables

Somewhere you're calling NewGalaTransaction(..., $guests, ...) are you passing an array or json at that point? Can you show that code?

mikenewbuild left a reply on How To Output A Json Array And Loop Through Variables

So is $guests already json encoded? Do you need to do:

$array = json_decode($guests);

If possible, passing a php array in initially would be more typical.

mikenewbuild left a reply on Hello Friends | Users Table Field Keeps Return True

@cronix quite. I know it shouldn't really matter in this case, but type is one of those keywords I avoid.

@respect - did you try casting that field to an integer as previously suggested?

mikenewbuild left a reply on Integrate Different Sources Of Notifications

If I'm honest it's hard to give really good advice without knowing the problem intimately. I'm not sure I understand what streams and fields are. I've operated a bit of a trial and error approach to solve these sorts of problems, as it tends to expose flaws I hadn't anticipated when it had all been perfect in my head :)

It might depend on how much you want to normalise the data. It sounds like you anticipate adding more notification types (sometimes this never comes true, and over eager abstraction becomes a burden - I've certainly fallen foul of that).

My advice would be to write a little code to test the viability of the option that seems most obvious to you. Write the api first (like the pseudo code above), and then figure out how best to implement it.

The code I would probably want to write is:


$stream->webhooks->each->notify($payload);

Wish I could give a less wooly answer :)

mikenewbuild left a reply on Hello Friends | Users Table Field Keeps Return True

You have stray characters in your fillable fields (commas, single quotes)


protected $fillable = [
        'name', 'email', 'password', ,', 'address',', 'type', 'category_id', , 'email_verified_at', ''api_reset_password_code', ];

Should be



protected $fillable = [
'name', 
'email', 
'password',
'address',
'type', 
'category_id',
'email_verified_at', 
'api_reset_password_code',
 ];

Not sure if that is a contributing factor?

mikenewbuild left a reply on In Practice, What Is Abstraction?

In your example, you could say OOP is the abstraction and PHP is the implementation ;-)

OOP is a concept and that can be implemented in multiple languages, but it has to conform to the concept of Classes/Methods/Inheritance etc. PHP implements these abstract concepts in a concrete way.

An abstract class specifically in PHP allows you to define some qualities that all classes derived from it will have.

Edit: importantly it doesn't say how you implement them, just that that all classes derived from it will inherit the abstract implementation by default.

It's worth looking into the discourse around the benefits of composition vs inheritance.

mikenewbuild left a reply on Integrate Different Sources Of Notifications

Someone posed a similar question recently - https://laracasts.com/discuss/channels/laravel/adding-multiple-notification-channels-to-the-user-model?page=1#reply=528379

My totally hypothetical approach would be to use a polymorphic relationship to represent each webhook. That would allow each type to manage their own implementation details eg. authorisation

mikenewbuild left a reply on Adding A Holiday Message

If you really don't want to store it in a database, you can use the cache instead. Makes it easy to set an automated expiry date too.

mikenewbuild left a reply on Prevent Multiple User Editing The Same Resource

In theory you can save a hidden input for when the form was accessed, and compare it to the updated at column.

05 Aug
2 weeks ago

mikenewbuild left a reply on Route('namedRoute') On $redirectTo Auth Module Isn't Working ??

You can't use functions in a property assignment like that. You could assign it within the constructor or a method as $this->redirectTo = route('admin::');

mikenewbuild left a reply on Adding Multiple Notification Channels To The User Model.

Yes, that's what I would expect from the docs. You can send one notice to multiple channels, not multiple notices to one channel in a single Notification (if I have understood correctly).

I think the way you have tried to write it would work more like:


$notification = new Notification;
$user->notificationChannels()->each(function ($item, $key) {
    $type = NotificationChannels::getDescription($item->type);
    $notification::route(strtolower($type), $item->url);
});

$notification->notify(new MyNotification());

But you might be limited to one route of each type.

This may not be the best way (!!!) but just off the top of my head I might try to implement a notify method on the NotificationChannels model itself, which is essentially a factory for the type of notification I want.

My (pseudo) implementation might look something like:


$user = $event->model->user;
$user->notificationChannels->each->notify(new MyNotification());

NotificationChannels.php


// etc

public function notify($notification)
{
    $this->getNotifiable()->notify($notification);
}

protected function getNotifiable()
{
    if ($this->type === 'email') {
        // return the mail notification instance
    }

    if ($this->type === 'slack') {
        // return the slack notification instance
    }
}


mikenewbuild left a reply on Adding Multiple Notification Channels To The User Model.

This is the reason why I think you will have to iterate over your channels and create a notification for each one.

This seems desirable to me, as it allows individual notifications to fail independently.

If you're looking to clean your code up a little you could implement polymorphism in your foreach loop.

04 Aug
2 weeks ago

mikenewbuild left a reply on Adding Multiple Notification Channels To The User Model.

If your user potentially has one or more notification types then you will have to do that iteration somewhere.

Unless you have a unique constraint on user_id and type there's no reason why the user can't have multiple webhooks for the same service.

Unless I'm missing something, I don't see an issue with your approach as you've described it.

mikenewbuild left a reply on UpdateOrCreate With JSON Fields (MySQL)

Syntax looks okay to me. Are you getting an error?

mikenewbuild left a reply on Suggestion: Add Dependency Versions To Series

The source code for that lesson is linked to in the video descriptions. You can inspect the composer package in the repo to see the dependencies.

mikenewbuild left a reply on What Test Choose Between Unit , Feature And Dusk Test ?

This is subjective, but I think the general consensus in the lessons on this site is to prefer feature tests, and use unit tests as part of a test driven approach. That's an approach that I have had some success with. I recommend the testing courses on this site as an introduction to that concept.

I have tried Dusk tests in projects but found little value personally, but there are scenarios where it's useful.

There are plenty of opinions about testing in general, so I think it comes down to working out the type of testing that gives you the most confidence in your code, and reduces the maintenance burden of your project. Easier said than done :)

mikenewbuild left a reply on Unit/Feature Test : Test If Radio Button Is Checked Or Not .

Glad you managed to get a bit further.

'category[]' => NULL, should eg. be in the format 'category' => [] as the data is already converted for you. To get the session errors, you will need to validate the same key 'category'

03 Aug
2 weeks ago

mikenewbuild left a reply on Unit/Feature Test : Test If Radio Button Is Checked Or Not .

That said, the test that is failing is not the one that you have included.

mikenewbuild left a reply on Unit/Feature Test : Test If Radio Button Is Checked Or Not .

A good way to debug this type of error is to add $this->withoutExceptionHandling() to your test temporarily.

mikenewbuild left a reply on Unit/Feature Test : Test If Radio Button Is Checked Or Not .

Looks like you have a typo in your route. Should it be route('projects.store') ?

mikenewbuild left a reply on Extending ArtisanServiceProvider

Try adding this autoload section to your composer.json

    "autoload": {
        "psr-4": {
            "BenSherred\\MakeModel\\": "src"
        },
    },

See: https://getcomposer.org/doc/01-basic-usage.md#autoloading

Nice idea for a package!

01 Aug
2 weeks ago

mikenewbuild left a reply on Q: BroadcastException - Fail Gracefully If No Pusher Server Is Running?

Ah yeah, I guess you can only catch exceptions that are part of a response. You could maybe create your own base Event class that extends the broadcast() method in the Dispatchable Trait and catch the error there? Not sure how valid that idea is though... might be a good place to start?

mikenewbuild left a reply on CORS Domain " Access-Control-Allow-Origin

1 - There's no tag.

2 - if it means scraping the data and storing that on a server where you can control CORS, then yes that would work.

31 Jul
2 weeks ago

mikenewbuild left a reply on Validating AJAX Post In Laravel Controller

The error says:

Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given, called in /Users/vladimircvetkovic/Desktop/Laravel/Sport/radar/Sportradar/app/Http/Controllers/AuthorBookController.php on line 80

That means the validate method is being passed an array instead of a Request object @ line 80. It looks to me like you may have something calling $this->validate() at line 80, but I can't see that in the code you've posted. For example make sure you're passing $request and eg. not $request->all().

mikenewbuild left a reply on Error Composer Install After Upgrade From 5.5 To 5.6

@cac it was a little while back, but I'm pretty sure I hit the same thing with env throwing me, when this was actually the root cause. I think after the changes with one of the projects I got caught in the trap of not being able to dump autoload or clear caches and in the end I may even have had to resort to manually deleting the cache files locally to resolve. This is maybe a couple of months ago so going from memory.

mikenewbuild left a reply on Validating AJAX Post In Laravel Controller

Check that you have the correct import statement in your controller

use Illuminate\Http\Request;

mikenewbuild left a reply on How Can This Code Be Refactored To Follow SOLID Principals

I should also say, that I think everybody struggles with this concept early on and it takes a lot of experience (suffering from making these very mistakes! ) to develop an ability to see the benefits of applying SOLID and the potential pitfalls the approach helps to prevent.

Trying to improve your own code is a great way to do it.

mikenewbuild left a reply on How Can This Code Be Refactored To Follow SOLID Principals

So all functions in this file have one concern which is the NPS score so reading the CSV file, importing to a database, calculation score...etc

I think you may have answered your own question? You could consider refactoring pretty much each method to separate classes, eg.

  • calculates an NPS score from a given dataset
  • parses CSV files
  • imports files periodically

How a score is calculated does not need to depend on the file system, the file type or how often files are imported.

If the file format changes to xml, you need to change a lot about this file, but if you separate these out, it would be easy to substitute one for the other. You would be able to do this without changing the file that knows how to calculate an NPS score.

I think once you extract these classes, you will be able to see more opportunities to improve the code (eg. reduce the indentation) as well as apply more SOLID principles.

I recommend you watch https://laracasts.com/series/solid-principles-in-php as an introduction to applying these principles in practise.

mikenewbuild left a reply on Error Composer Install After Upgrade From 5.5 To 5.6

@cac did you try following the SO link I posted. It's regarding the change to TrustedProxies middleware in 5.6 - that env error fooled me when I upgraded as it hid the real error and following the points in that SO answer resolved for me.

30 Jul
2 weeks ago

mikenewbuild left a reply on How To Run App With Puppeteer On Remote Server

I would recommend that you first follow the setup instructions on https://github.com/spatie/browsershot step by step to see if it resolves the issue. It includes instructions for all the packages required on a Ubuntu server.

29 Jul
3 weeks ago

mikenewbuild left a reply on CORS Domain " Access-Control-Allow-Origin

As far as I'm aware it needs to be in the http response header, that's one of the benefits. You mentioned that you were trying to get JSON not HTML though? Are you trying to scrape data from someone else's site - or is it meant to be a public endpoint?

mikenewbuild left a reply on How To Run App With Puppeteer On Remote Server

It sounds like you may still need to "build" your js file for production.

Be sure to run the production command to compile your app's js file and then deploy it to the server.

npm run prod

Edit: just had a quick look at the browsershot package and checking that you have already followed the instructions to install Chrome on your server?

mikenewbuild left a reply on Getting All Data From Database

$books = Book::with('author')->all();

foreach ($books as $book) {

 // now you can do
  $book->author->name;
  // etc
  $book->release_date;

}

mikenewbuild left a reply on Writing A Policy For Voting Poll

If you have your relationships set up properly, you may also be able to express it as

abort_unless($poll->is($options->poll), 403);

https://laravel.com/docs/5.8/eloquent#comparing-models

mikenewbuild left a reply on Writing A Policy For Voting Poll

Of course, @click is right. I think you have a couple of options. You can use the policy, make $user optional and pass in the $poll and $option_poll_id as the array and do the check.

But you could also avoid using a policy and do the check in the controller.

if ($id !== $vote_options_test->poll_id) {
  abort(403);
}

or if you're fancy

abort_unless($id === $vote_options_test->poll_id, 403);

https://laravel.com/docs/5.8/helpers#miscellaneous

mikenewbuild left a reply on Page View Increment Not Working In Laravel

No worries, glad to help :)

mikenewbuild left a reply on Writing A Policy For Voting Poll

Ah okay. I'm confused about what's a poll id and what's a vote id.

To debug you could try to dd() the $id and then the $vote_options_test->poll_id to check they match as expected.

mikenewbuild left a reply on Page View Increment Not Working In Laravel

IIRC increment doesn't refresh the model. You may need to do something like:

$advert = Advert::where('slug', $slug)->first();

$advert->increment('page_view');

$this['views'] = $advert->fresh()->page_view;

mikenewbuild left a reply on Personal Access Token

I believe that is expected behaviour.

https://laravel.com/docs/5.7/passport#personal-access-tokens

"Personal access tokens are always long-lived. Their lifetime is not modified when using the tokensExpireIn or refreshTokensExpireIn methods."

Potential solution here: https://stackoverflow.com/a/54519416 - I have not tried it myself though, sorry.

mikenewbuild left a reply on Getting All Data From Database

You may prefer to query all books that have an author, sort by author and loop through the result. It would remove a nested foreach and help you avoid potential n+1 issues in your query.

mikenewbuild left a reply on Method For Reusing Test Data?

In your example the assertions are all the same, so you could also compact them into a single test and use a data provider. It's actually a good use case for a data provider.

However, I personally prefer the solution with the local method and multiple tests unless I'm dealing with dozens of cases.

Please mark answer correct to help others find the solution - thanks.