goldtaste

goldtaste

Member Since 3 Years Ago

Experience Points
19,010
Total
Experience

990 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
160
Lessons
Completed
Best Reply Awards
3
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.

Level 4
19,010 XP
Dec
14
21 hours ago
Activity icon

Replied to Many To Many Relationship

Try:

public function store(Request $request)
{
    $password = Str::random(6);

    $this->validate($request,[
        'firstname' => 'required|string|max:255',
        'lastname' => 'required|string|max:255',
        'phone' => 'required',
    ]);

    $patient = Patient::where('phone', '=', $request['phone'])
                                ->first();

    if($patient === null){
        $patient =  Patient::create([
        'firstname' => $request['firstname'],
        'lastname' => $request['lastname'],
        'email' => $request['email'],
        'phone' => $request['phone'],
        'sexe' => $request['sexe'],
        'password' => Hash::make($password),
    ]);

    $doctor = auth('doctor')->user();
    $patient->doctors()->attach($doctor);

    return $patient;
}
Activity icon

Replied to Htmlspecialchars() Expects Parameter 1 To Be String, Array Given

@zyxxyzyxz I know these things can be annoying, but you should probably remember that youre using a free framework - which many of us think is pretty great - and be a bit more appreciative.

Dec
11
3 days ago
Activity icon

Awarded Best Reply on Api Controller

Yes, you probably want separate controllers for each of these. It's likely that you will only end up calling two or three end points from a page (I'm guessing your are using vue or some sort of SPA) at the same time. Which isn't too much of a problem.

If you do end up making lots and lots of calls at the same time, then you may want to consider some sort of facade controller.

I would also recommend reading up on REST apis. May also be worth checking to see if there is anything on laracasts video section about creating apis. I'm pretty sure there will be.

Activity icon

Replied to Api Controller

Yes, you probably want separate controllers for each of these. It's likely that you will only end up calling two or three end points from a page (I'm guessing your are using vue or some sort of SPA) at the same time. Which isn't too much of a problem.

If you do end up making lots and lots of calls at the same time, then you may want to consider some sort of facade controller.

I would also recommend reading up on REST apis. May also be worth checking to see if there is anything on laracasts video section about creating apis. I'm pretty sure there will be.

Activity icon

Replied to How To Structure My App

I would probably add some extra non db fields to the report class to hold info from the api calls. You could make these public class properties. Or you may want to make them private/protected and add setters and getters. Note, these fields will never be saved to the db.

I would then have a separate generator/builder class (maybe a service class) that is responsible for making the api calls and loading the eloquent model from the db. The report generator class will effectively build your report model into something you want to use. Once you have populated the report you will have a method in your generator class to get the built eloquent model (db stuff and api info). You can then call the ReportGenerator class in the controller.

It's probably a bad idea to do the generation logic in controller methods for re-use purposes. You may end up copying the api call methods between controllers. As suggested, I would just put this in a class. Better for re-use

Depending on how complicated the api is, you may want to create a separate class for calling the api and including those in the generator/builder class.

Hope that sort of makes sense.

Dec
05
1 week ago
Activity icon

Replied to Which Route Is Better?

Ahh, haven't seen the second type before. Sounds like - from above - either will work.

Do you know that you don't need to add the .php extension to your route?

You have

Route::get('/used-equipment.php', '[email protected]')->name('usedequipment.index');

In your browser you would go to: https://mysite.com/used-equipment.php

If you do:

Route::get('/used-equipment', '[email protected]')->name('usedequipment.index');

In your browser the following would work: https://mysite.com/used-equipment

Most people don't include the extension these days for urls.

Activity icon

Replied to How To Mock Model's Static Function In Phpunit?

I think it is generally very hard to mock static methods in phpunit. There is an article about it here: http://miljar.github.io/blog/2014/01/29/phpunit-testing-static-calls/. And it looks like a major hassle.

The best thing to do is to generally try and avoid static methods. Also, in an ideal scenario you would mock out objects that speak to the database. But you are using eloquent and doing both of those things really doesn't make sense. Just work with what you've got and unit test with the db involved.

As @bobbybouwmann mentions, you should set up a separate db for testing (in memory or sqlite, so it's faster) and you will be able to refresh it for each test.

Activity icon

Replied to Easiest Way To Query Based On A Relationship

As an alternative, you could do

public static function getAdmins()
{
    static::whereHas('roles', function (Builder $query) {
        $query->where('name', 'admin');
    })->get();
}

probably not as simple as Nakov's solution, but if you don't like the idea of using another model in your model, this may be a solution.

Dec
04
1 week ago
Activity icon

Replied to Help With Pattern For Project

Hi @andrethedev the reason why it is good to pass in dependencies through the constructor is that you can then mock them out in tests. At the moment if you wanted to test CreateContractService then it's going to run all the dependant services. This includes addMembershipCardToMember. Does this involve hitting a payment provider? If it does, obviously you wouldn't want to do that in your tests. Although you could test CreateContractService if you mock out that class.

Also, if you use an interface for something like the ContractRepository, you can easily switch out the repository type. For example, you could switch from a mysql repository to a mongo db one more easily. At the moment if you were to change your repository, you would have to hunt through every class were you instantiate one and update the code. If you use an interface and dependency injection, you wouldn't need to do that. To get the concrete class in the first place you can add it as an argument to the controller's action method and let laravel's ioc container take care of deciding which concrete class to use. See : https://laravel.com/docs/5.7/container#binding-interfaces-to-implementations for more on that. That potential ly means one change to completely switch out your repository.

As for the for loops, either way will probably work. Though, I wouldn't worry about repeating a for loop - will make very little difference to code execution time.

Dec
03
1 week ago
Activity icon

Replied to Help With Pattern For Project

Just a couple of notes.

It may be an idea to make your ContractRepository, AddMemberToContractService, etc. implement interfaces or extend abstract classes. Program to an interface not an implementation.

And taking the above into account, you should also probably pass them in through the CreateContractService constructor (dependency injection). Or add methods to the CreateContractService so you can set them (again dependency injection). That will make testing easier if you want to mock out certain classes. The will also promote loose coupling.

You can probably create these sub classes in the first instance through the controllers action method arguments and using laravels ioc container. Or you could just create them in the action method. Think I like the idea of passing them in as arguments more, though. In laravel with controller action method dependency injection you can specify which concrete classes to use for an interface.

I would remove the foreach method and just put that in the AddMemberToContract class as e.g. $this->addMemberToContract->addMembersToContract(id, $data['member_list'])

Apart from that. I think it all looks fine.

You could use a form request to handle validation in the controller. Don't think it will hurt having some code in there.

Activity icon

Replied to Laravel Pagination Render()

see https://laravel.com/docs/5.8/pagination#displaying-pagination-results scroll down a bit to Customizing The Paginator URI

Activity icon

Replied to Laravel Pagination Render()

Yeah, the default php object doesn't have a render method. Rather than returning an array/stdObject of pagination properties that you have built up, you may be better returning a paginator.

There's more info here: https://laravel.com/docs/5.8/pagination#introduction

You may be re-inventing the wheel as is with the $res array. Can't you just return the paginator?

Activity icon

Replied to Laravel Pagination Render()

Your are returning an array that has been converted to the default php stdObject through the json encoding/decoding. stdObject doesn't have a render method.

Activity icon

Replied to Scalability On Demand?

Have you looked into bref for serverless PHP. Then you could pick your cloud provider (e.g. Amazon AWS). I have not used it myself, but think it is quite popular.

Dec
02
1 week ago
Activity icon

Replied to SOLID Design Principles And Data Manipluation

For handling the conversion in the first instance you could even go down the decorator route and have a price decorator that implements the request interface. And just do it in the controller.

Activity icon

Replied to SOLID Design Principles And Data Manipluation

If your product price is in cents, you could alway use a mutator to make it easier to get the dollar price in views etc.

public function getPriceInDollarsAndCentsAttribute()
{
    return $this->price / 100;
}

So in your view:

<p>price : {{$product->priceInDollarsAndCents}}</p>

May save a few extra calculations in your front end code.

Dec
01
1 week ago
Activity icon

Replied to Avoiding Cache Slams

Ahh, this code is not in the controller? You could throw an exception in the method and then handle it in the controller with a redirect, or error message that you pass to the view and handle it there.

Activity icon

Replied to Avoiding Cache Slams

It's not something I have looked at before, but could you put some sort of flag into the cache.

So

$cacheKey = 'randomCacheKey'.
$cacheTemporarilyLocked = 'tempLock';

if(Cache::has($cacheKey)) {
 return Cache::get($cacheKey);
}

if(Cache::has($cacheTemporarilyLocked)) {
 // throw exception or do redirect to we are busy page. back soon.
}

Cache::set($cacheTemporarilyLocked, true);
//do some work
$valueToCache = $this->someComplexTask();
Cache::set($cacheKey, $valueToCache);

Cache::forget($cacheTemporarilyLocked);

return $valueToCache;

Haven't given it too much thought or tried it, but it may be a solution? Possibly?

Activity icon

Replied to What To Return If No Record Was Found

My point was that he should just do the null check or throw and exception. And I'm only updating my replies to correct the english.

Activity icon

Replied to What To Return If No Record Was Found

Your quote:

@goldtaste people use NullObject pattern to cut down on if statements and try catch blocks. What you suggest will just increase the count.

Activity icon

Replied to What To Return If No Record Was Found

I'm happy to create classes when they are needed and certainly not reluctant to create them to improve flexibility. But there has to be a limit. Like creating a bizillion classes because I want to use a null object when I probably don't need one. Possibly 5 website if statements vs 1000000 classes.

Activity icon

Replied to What To Return If No Record Was Found

Yupp, over complicated. All these extra classes because you don't want to do a fairly reasonable if check for a null or do a bit of error handling. Good luck following that logic. Also, I think we better call it a day or this thread will go on forever.

Activity icon

Replied to What To Return If No Record Was Found

I would want to see details of the featured product on the home page or a message saying that there isn't one, not get redirected. Or see featured product name: blank. Also with repositories that was just an example because you were complaining about hard coding.

Activity icon

Replied to What To Return If No Record Was Found

Lol.

 if ($featuredProduct->notFound()) {
        return redirect($featuredProduct->getShowUrl());
 }

I thought you were getting rid of if statements.

It is pretty common to have a featured products page. I wouldn't call it hard coding.

Instead of using an eloquent model - which is a very common thing to do in laravel - you could inject a Product repository if you were wanting to improve flexibility. Obviously using an interface in the method arguments.

But I think you are over complicating things. Should a product know about which views to use? What if the view name changes? You would need to update the class. Most people specify views directly in the controller. Is that really a bad thing to do?

Also, what if a summary of the featured product needs to be added to the home page? A null object isn't going to be any good there - unless you put an if in the view.

Also, what happens if you now needed to add both a latest and featured product. Your class would break the open/closed principle.

Activity icon

Replied to Which Features Are You Missing In Forums?

Just spotted that there is a heart button, so scrap that.

Activity icon

Replied to Which Features Are You Missing In Forums?

A small one. Think it would be good if there was a like button on forum posts and answers. Apart from that, I think the content of the videos is great. Possibly a couple more guest speaker videos would be good.

Out of interest, why are you doing a poll? Do you work for laracasts.

Activity icon

Replied to What To Return If No Record Was Found

Sorry, just realise the original poster was talking about latest and not featured products, but my logic still applies.

Activity icon

Replied to Creating User For API Giving Error

Glad you got it working. +1

Activity icon

Replied to Creating User For API Giving Error

Ahh, sorry. Didn't spot that you were posting the user. Yes, @nakov answer makes the most sense. You created the user and then tried to re-register them.

Activity icon

Replied to Creating User For API Giving Error

Check out : https://laravel.com/docs/5.8/http-tests#testing-json-apis

So instead of

 $response = $this->postJson('/api/register', $user);

do

$response = $this->json('POST', '/api/register', ['name' => 'Sally', 'email' => '[email protected]', 'password' => 'mypassword']);

You are going to have to pass some valid data if you want the test to pass. You should also write a test where you pass invalid data and check for an exception. 422? 403?

Activity icon

Replied to Creating User For API Giving Error

You could pass some valid test data using the call method:

https://laravel.com/docs/5.2/testing#custom-http-requests

Probably a better test.

Then you could write a test that passes some bad values and test for an http error. think it might be 403 in this case?

Activity icon

Replied to What To Return If No Record Was Found

@bugsysha It's a made up method for this example. I assume the poster has a similar method that get's the site's featured product. In my example, it would simply return a product - could be any of the products - that is flagged as the website's featured product. I'm guessing it will be flagged in the db.

So it simply returns a product (that is somehow flagged as featured.)

Activity icon

Replied to What To Return If No Record Was Found

@bugsysha . Sorry, I don't understand what you mean. If you have a dedicated featured product page like above, how would you handle this with a null object? It's a pretty common scenario. You would need to add some sort of if to check if the null object was empty in the view. Or if in the controller add a check to see if the product url is not-found and redirect instead of loading the view.

As mentioned, the null object pattern shouldn't just replace exceptions.

Activity icon

Replied to What To Return If No Record Was Found

I'm guessing he has a controller method like:

public function show()
{
    $featuredProduct = Product::getFeaturedProduct();
    return view('featured-product', compact('featuredProduct'));
}

Can you explain how your null object would work for that.

Activity icon

Replied to What To Return If No Record Was Found

@bugsysha Will it? Give it a bit of thought and get back to me.

Activity icon

Replied to What To Return If No Record Was Found

@bugsysha . What if there is a featured product page? Your method won't work on that page.

Activity icon

Replied to What To Return If No Record Was Found

@bugsysha As mentioned this is how laravel handle findOrFail. They don't return a null object.

The NullObject Pattern is a valid pattern, but you don't want to over use it. It's not a catch all. It's good if you have a null logger for example.

In this case, the poster will want to handle a not found featured product and display an appropriate error page or display a message on the page saying that there is no featured product. How would you do that with a null object in this case? Just print blank values? Somehow I doubt he would want to do that.

Also, you don't always need try catch blocks. In laravel - maybe not in this case - you can let the error propagate up and let the framework handle the exception. For example, findOrFail and 404 exceptions.

Activity icon

Awarded Best Reply on Where To Begin?

If you know html & css, I would probably start with an easy introduction to php at somewhere like w3schools. If you have programmed before then it shouldn't take too long. Maybe a day or two. I think the php stream on laravel is maybe a little too advanced for someone without much php experience, but a great place to go if you know a little.

Then I would do the php stream on laracasts. And then finally, the laravel stream on laracasts. You really need to have a fairly good understanding of php before tackling laravel.

With all that said, you probably can't find a better place to learn php and laravel than on laracasts.

Good luck with your studies ...

Activity icon

Replied to Where To Begin?

If you know html & css, I would probably start with an easy introduction to php at somewhere like w3schools. If you have programmed before then it shouldn't take too long. Maybe a day or two. I think the php stream on laravel is maybe a little too advanced for someone without much php experience, but a great place to go if you know a little.

Then I would do the php stream on laracasts. And then finally, the laravel stream on laracasts. You really need to have a fairly good understanding of php before tackling laravel.

With all that said, you probably can't find a better place to learn php and laravel than on laracasts.

Good luck with your studies ...

Activity icon

Replied to SPA Laravel And Vue.

Hmm, I guess they need to get stored somehwhere. If not local storage, where should they be stored? Don't mean to rude. Would actually like to know. What do the forums suggest?

Activity icon

Replied to What To Return If No Record Was Found

Eloquent has findOrFail methods that throw an exception for things like this. May be better throwing an exception that you can handle than returning null as the fact that you return a null may not be clear to future people using the class api. If you are using nulls, you probably want to make that clear in your method return type by specifying that it has a nullable return type e.g. ?Product. At least with exceptions it's pretty clear what is expected and your IDE will pick up that your method can throw exceptions and that the client code should probably handle them.

In your case, unfortunately, you would have to update all your existing calling code to handle exceptions. Guess that would be the same for handling null. Just think exceptions are a bit clearer.

Of course, if the null object suggested by others works for you, then you probably won't have to bother with the above.

Activity icon

Replied to SPA Laravel And Vue.

There's a good article on medium.com about using jwt tokens with laravel and vue: https://medium.com/@ripoche.b/create-a-spa-with-role-based-authentication-with-laravel-and-vue-js-ac4b260b882f

It discusses using the websanova/vue-auth package for handling authentication on the front end, so you don't need to worry about storing tokens etc. It's all done for you. Haven't dug into the code so not too sure what it's actually doing with them.

Nov
29
2 weeks ago
Activity icon

Replied to How To Get Nested Errors Into Vue

Laravel returns errors as an array of arrays. I use loadash to flatten this into one big array:

const errors = _.flatten(error.response.data)

This is good if you are just wanting to list the errors in an unordered list at the top of the page for example .Probably won't be the best approach if you want to put errors below text fields etc.

You will need to add vue-loadash to your site for this to work: https://www.npmjs.com/package/vue-lodash

Nov
27
2 weeks ago
Activity icon

Replied to Splitting Up Models Into Multiple Files Due To CodeLinting Smell Rule

I guess relationships and attributes should definitely stay in the class.

If you have a group of related scopes you may want to add them to a trait. But if they aren't really related I would keep them in the class.

As for other methods, again if they are related, I guess you could extract them to a trait or their own class.

Can you not just ignore the warnings, or is it stopping some sort of build?

Activity icon

Replied to Getting Average Scores From Objects In A Collection

The following may work, but may not be the best solution;

$collection = Model::where(‘user_id’, $id)->pluck(‘question_answers’);

$sum = 0;

foreach($collection as $questionAnswer){
    $questionAnswer = json_decode($questionAnswer);
    $sum += $questionAnswer->{'Question One'};
}

$average = $sum / $collection->count();

echo $average;
Activity icon

Replied to Getting Average Scores From Objects In A Collection

Just to clear things up, I think what @twoarmtom is saying is that he is storing json objects in the database. Is that correct @twoarmtom?

If that's right the collection average methods aren't going to work for you.

You will probably have to loop through the collection and json_decode each item. In your loop you can build up count and total and use these to calculate average the good old fashioned way.

Nov
21
3 weeks ago
Activity icon

Replied to Eager Loading Where Query Returns Empty Array

Just realised my query will only work if you only have one businessunit for a site. Can multiple sites have the same businessunit?

I think your query looks fine (get me all courses that are linked to any sites that have a businessunit named x)

Have you tried running the sql against the db:

dd(Course::whereHas('siteObject', function ($query) use ($queryParams) {
$query->where('businessunit',$queryParams['filterByBusinessUnitShortName']);
 })->toSql());

Are you sure that the sites in question definitely have courses?

In your site model do you have the following method:

 public function courses()
    {
        return $this->hasMany('App\Course');
    }
Nov
20
3 weeks ago
Activity icon

Replied to Eager Loading Where Query Returns Empty Array

Try

$site = Site::where('businessunit',$queryParams['filterByBusinessUnitShortName'])->with('courses')->first();

return $site->courses;
Activity icon

Replied to Connection Refused In Laravel Mysql Project

Hmm, it may be worth creating an non laravel test php page where you try and connect with PDO or something - just to see if you can connect to mysql from php. May allow you to figure out if the problem is with the server. I guess it doesn't help that message is quite vague. I guess there is not much you can do about that, though.