goldtaste

goldtaste

Member Since 3 Years Ago

Experience Points
20,800
Total
Experience

4,200 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
165
Lessons
Completed
Best Reply Awards
5
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 5
20,800 XP
Dec
30
4 weeks ago
Activity icon

Awarded Best Reply on Creating A Simple Task List But Getting An Error

As @sergiu17 mentions, you will need a Task class. Usually, if you are using eloquent, these will have the App namespace.

If you do have a task class, check what namespace you are using and import that at the top of your controller;

e.g.

use App\Task;

or replace this with whatever namespace it uses

<task-class-namespace-goes-here>\Task;

If you have a task class and it doesn't have a namespace, then add the following:

use Task;
Dec
29
4 weeks ago
Activity icon

Replied to Creating A Simple Task List But Getting An Error

As @sergiu17 mentions, you will need a Task class. Usually, if you are using eloquent, these will have the App namespace.

If you do have a task class, check what namespace you are using and import that at the top of your controller;

e.g.

use App\Task;

or replace this with whatever namespace it uses

<task-class-namespace-goes-here>\Task;

If you have a task class and it doesn't have a namespace, then add the following:

use Task;
Activity icon

Replied to Creating A Simple Task List But Getting An Error

The error relates to your task model. You will need to add the following to the top of your controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Task;

And for the flash part do

$request->session()->flash('success', 'Created Task Successfully');
Dec
22
1 month ago
Activity icon

Replied to Repository Pattern With The Same Interface

As @nakov mentions there is absolutely nothing wrong with sharing an interface if your classes implement the same methods. And it sounds like your repositories are only going to stick with these methods, so what you are doing is fine and @nakov's approach sounds like a sound one.

However, if you do find yourself later adding extra methods to the interface which some of your repositories just provide empty implementations for, you may well want to re-visit and go down the multiple interface route. @bugsysha mentions this in one of his replies: Just be careful for Interface Segregation and you are all good.

Activity icon

Replied to Repository Pattern With The Same Interface

Also, I didn't know about contextual binding. Useful to know.

Activity icon

Replied to Repository Pattern With The Same Interface

Yupp, contextual binding may be better in that case. But I suspect that you would probably end up having to have a separate interface for each of these types in reality. Although, the original poster did not actually discuss a need for this.

Activity icon

Replied to Repository Pattern With The Same Interface

I wouldn't expect the App\Repositories\UserRespositoryInterface and App\Repositories\Post\RespositoryInterface to be empty although they would in this case share common methods through the CrudRepositoryInterface. It's likely there will be methods that one has that the other doesn't. As a silly example : getMostLikedPost();

Activity icon

Replied to Repository Pattern With The Same Interface

You could create an interface for each of the types:

e.g. App\Repositories\UserRespositoryInterface, App\Repositories\Post\RespositoryInterface

And just get those interfaces to extend the CrudRepositoryInterface.

Dec
18
1 month ago
Activity icon

Replied to Git Stash

I don't think you can add a message. But you can see how to apply specific stashes here:

https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning

Though, most of the time you will probably just want to add the last stash.

Yes, if you stash, your branch will go back to the last commit. If you re-apply the stash then you get back the changes that you put in the stash; i.e. your uncommitted changes. If you decide you don't want to reapply the unsaved work, just don't reapply the stash. You can also delete the stash if you're sure you don't want the changes.

Activity icon

Replied to Paypal IPN , Is It Needed? Please Answer

Have you looked at (Paypal Checkout) https://developer.paypal.com/docs/checkout/integrate/

Looks like that is the new way of doing things instead of express checkout. Also looks like it should be fairly easy to setup.

Activity icon

Replied to Running Tests In Homestead Painfully Slow

Sorry, just spotted that you are using sqlite

Activity icon

Replied to Running Tests In Homestead Painfully Slow

Does sort of sound slow. Although usually, you do want to refresh and seed the db for tests involving eloquent.

Do you know that you can filter tests, so you don't need to run all tests at once.

./vendor/bin/phpunit --filter=MyTestClass

Also, are you using sqlite for your db. If not, that will speed things up:

https://mauricius.dev/sqlite-in-memory-database-for-unit-tests-in-laravel/

Activity icon

Replied to Git Stash

Say you have a shopping site and want to add an experimental new feature (like special offers for example).

You would create a new branch from the master (or develop) branch.

Make sure you are on the master branch.

git checkout master

Now create a new feature branch for your experimental code

git checkout -b special-offers

Do your new work on this branch, committing as you go along. Once you have finished the work on the new feature branch test that it works (locally and on a test server if you have one).

If you are not happy with the new work (you don't think customers will like special offers) just delete the branch.

git checkout master
git branch -d special-offers

If however you are happy with the branch, then you can merge it into master

git checkout master
git merge special-offers

So for new features. Create a feature branch and if happy merge into your main branch.

Okay, so say you are still working on the new branch (you have not deleted or merged it yet) and someone tells you have a bug and you need to switch back to master and fix the bug, git will not allow you to switch back to master when you have uncommitted changes, so you have two options 1. commit the code that you're in the middle of working on or 2. stash the changes for later:

git stash

Now, that you have stashed (or committed) you can switch back to master:

git checkout master

Fix the bug (ideally you would create a separate hotfix branch).

Once you have fixed the master branch you can go back to working on the new feature. If you committed the changes, you won't need to do anything. If however you stashed them, you will need to reapply them if you want to get back to were you left off.

git checkout special-offers
git stash apply

Usually you only commit when you have stuff working. If you are in the middle of some unfinished code and need to switch branches you may prefer to stash the changes. Although it definitely won't be a disaster if you just go ahead and commit them.

Dec
16
1 month ago
Activity icon

Replied to Memory Exhausted After So Much Loops. Back To Eloquent

Chunking is not something I have used (still fairly new to laravel), but I have read about it and it may help in your case.

See: https://laravel.com/docs/5.8/eloquent#chunking-results

and : https://laraveldaily.com/process-big-db-table-with-chunk-method/

Note: It may mean doing the eloquent query in your blade file. I think this is generally frowned upon, but think it won't be useful in the controller. As I think someone else mentions, the problem probably isn't because of the loops/processing, it's more to do with the amount of data that you are trying to hold in memory.

Activity icon

Awarded Best Reply on 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;
}
Dec
14
1 month 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
1 month 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 month 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 month 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 month 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 month 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 month 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.