nickywan123

nickywan123

Member Since 7 Months Ago

Experience Points
9,110
Total
Experience

890 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
2
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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 2
9,110 XP
Oct
12
2 weeks ago
Activity icon

Started a new Conversation Test-Driven Laravel By Adam Wathan

Was wondering anyone followed this course?

Is this course for beginners who wants to learn TDD ?

I tried following the laracast build a forum with TDD course and it's an advanced course and felt overwhelming.

Oct
06
3 weeks ago
Activity icon

Replied to Eager Loading In Laravel

So rule of thumb is to always use eager load if I will access a relation of any kind?

Activity icon

Replied to Eager Loading In Laravel

Okay I think I grasp the concept now. When it involves a collection of data, it should be inside foreach right?

@foreach($purchase->orders as $order)

Even with this case, this can result in the N+1 problem as it is executing one query for every order that belongs to the purchase?

Activity icon

Replied to Eager Loading In Laravel

Well I follow the Purchase model convention. A single purchase can have many orders.

So it will look like this in the model:

public function orders(){
............
}

Or do I need to name it singular instead?

Activity icon

Replied to Eager Loading In Laravel

Cool. Is there a difference between this two ways:

@foreach($purchases as $purchase)
.........
...{{$purchase->purchase_number}
  @foreach($purchase->orders as $order)
	.......{{$order->order_number}}
	@foreach($order->items as $item)
	.........{{$item->item_name}}
	@endforeach
  @endforeach

@endforeach

or

@foreach($purchases as $purchase)
.........
...{{$purchase->purchase_number}
  	{{$purchase->orders->order_number}}
	
	.....{$purchase->orders->items->item_name}}
	
@endforeach

Will both also yield the same result?

Or an easier example you gave was this:

foreach ($books as $book) {
    echo $book->author->name;
}

vs

foreach ($books->author as $author) {
    echo $author->name;
}

Like which way is better to write since both ways give the same result right?

Whether accessing the relationship inside the foreach brackets or inside, it will also give the N+1 problem right?

Activity icon

Replied to Eager Loading In Laravel

I see. Maybe a different example would be easier to highlight the issue.

@foreach($purchases as $purchase)
.........
...{{$purchase->purchase_number}
  @foreach($purchase->orders as $order)
	.......{{$order->order_number}}
	@foreach($order->items as $item)
	.........{{$item->item_name}}
	@endforeach
  @endforeach

@endforeach

In this case, in my controller, I could eager load orders and items like sometime like this:

$purchases = App\Models\Purchase::with('orders.items')->get();

return view(.........., compact('purchases'));

Without eager loading, it will result in the N+1 issue too right?

Activity icon

Replied to Eager Loading In Laravel

So when is the scenario that eager loading should come to play?

Activity icon

Replied to Eager Loading In Laravel

@sinnbeck So if i do it this way:

What if it's this way:

foreach ($books->author as $author) {
    echo author->name;
}

Will this also result in n+1 problem?

Assuming in the controller, I just passed in all books without eager loading.

Activity icon

Replied to Eager Loading In Laravel

@laracoft @snapey I did read it but got confused with the scenario of using it to pass it to the view. So only the lazy loading happens if it's inside the foreach loop?

What if it's this way:

foreach ($books->author as $author) {
    echo author->name;
}

Will this also result in n+1 problem?

Oct
05
3 weeks ago
Activity icon

Replied to Eager Loading In Laravel

So even if I do:

$books = App\Models\Book::all();

$author = $books->author()->get();

return view(........)-->with('author',$author);

Does this count as eager load?

Activity icon

Started a new Conversation Eager Loading In Laravel

Based on the documentation, eager loading solves the n+1 problem and it looks something like below:

$books = App\Models\Book::with('author')->get();

foreach ($books as $book) {
    echo $book->author->name;
}

I also tried to use it this way:

$books = App\Models\Book::all();

return view(........)-->with('books',$books);

In the second scenario, would it be considered as. eager loading as well?

Sep
29
1 month ago
Activity icon

Replied to Good Course For Laravel 7?

Yes I feel like many developers fall into the trap in real life of not writing tests, don't know why but it does save you from a headache in a long run by writing tests.

Activity icon

Replied to Good Course For Laravel 7?

Actually I am halfway through the laracast build a forum with laravel with TDD so it covers the scope of writing tests as well.

Activity icon

Started a new Conversation Good Course For Laravel 7?

A while back, I completed Laravel from Scratch in Laracast and now I want to sharpen my skills more and looking for other courses. Many courses in udemy,freecodecamp,etc are using older version of laravel and with the newest version laravel 8 being released, it is still very new so I want to stick with 7 for the time being.

Any recommendations?

Aug
22
2 months ago
Activity icon

Replied to Vue Version Mismatch Packages

@sinnbeck I found a work around way that if I update it to this version:

npm install [email protected]

then i can do a npm run watch

But my package.json still shows my vue version to be 2.5.17

Activity icon

Replied to Vue Version Mismatch Packages

@sinnbeck Yes I did though.

Activity icon

Started a new Conversation Vue Version Mismatch Packages

I installed vue in my laravel app and everytime I run npm run watch, I get this error:

ERROR in ./resources/js/components/Flash.vue
Module Error (from ./node_modules/vue-loader/lib/index.js):


Vue packages version mismatch:

- [email protected]
- [email protected]

This may cause things to work incorrectly. Make sure to use the same version for both.
If you are using [email protected]>=10.0, simply update vue-template-compiler.
If you are using [email protected]<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.

however in my package.json:

 "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.5.2",
        "cross-env": "^7.0",
        "jquery": "^3.2",
        "laravel-mix": "^5.0.5",
        "lodash": "^4.17.20",
        "popper.js": "^1.12",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.20.1",
        "sass-loader": "^8.0.0",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.5.17"
    }

The version of the vue is different to that of the error message. How do I fix this?

Aug
17
2 months ago
Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation: 19 NOT NULL Constraint Failed: Activities.user_id

@sinnbeck Does laravel 7 support all 3?

Tested them,

Doesn't work and says:

ErrorException: Trying to get property 'id' of non-object

Although i dump and die them and it returns a value of 1 as well.

Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation: 19 NOT NULL Constraint Failed: Activities.user_id

It keeps returning null even though I dd(auth()->id()) and it return value of 1.

If I hardcode both user_id set to 1 then it works.

Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation: 19 NOT NULL Constraint Failed: Activities.user_id

@snapey Yes I already have a guarded in my Activity model.

I don't have a relationship for

activities()

yet as I figured I could get the auth id without it. I followed the tutorial and it seems to work for him:

https://laracasts.com/lessons/build-an-activity-feed-in-laravel

Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation: 19 NOT NULL Constraint Failed: Activities.user_id

I switched to like. below:

$this->actingAs(factory('App\User')->create());

so the user is authenticated.

Cause dd(auth()->id()) will return id as 1. It's not saving to database.

Activity icon

Started a new Conversation SQLSTATE[23000]: Integrity Constraint Violation: 19 NOT NULL Constraint Failed: Activities.user_id

I created a test case that when a new record of Thread is inserted into thread table, it should also populate my activities table.

Test case:

class ActivityTest extends TestCase
{
    use DatabaseMigrations;
    
    /** @test */
    public function it_records_activity_when_a_thread_is_created(){
        $this->withExceptionHandling();
        $this->be($user = factory('App\User')->create());

        $thread= factory('App\Thread')->create();

        $this->assertDatabaseHas('activities',[
            'type' => 'created_thread',
            'user_id' => auth()->id(),
            'subject_id' => $thread->id,
            'subject_type'=>'App\Thread'
        ]);
    }
}

Thread model:

....
protected static function boot(){
        parent::boot();

        static::addGlobalScope('replyCount',function ($builder){
            $builder->withCount('replies');
        });

        static::created(function($thread){
        
            Activity::create([
            'user_id' => auth()->id(),
            'type' => 'created_thread',
            'subject_id' => $thread->id,
            'subject_type'=>'App\Thread'

            ]);
        });
    }

So running the test case says the user id column in activities table being inserted is null. However, I use

auth()->id()

which should return a value.

I tried replacing it to:

  Activity::create([
            'user_id' => 1,
            'type' => 'created_thread',
            'subject_id' => $thread->id,
            'subject_type'=>'App\Thread'
            ]);

and it worked. I tried dd(auth()->id()) and it also returns 1. Any idea why it is not working or did i overlook something?

Aug
11
2 months ago
Activity icon

Replied to Eager Loading Count Not Working

@tisuchi Nope, but I followed @michaloravec solution and it seems to fix the problem.

Activity icon

Replied to Eager Loading Count Not Working

@michaloravec $with is not working anymore?

Activity icon

Started a new Conversation Eager Loading Count Not Working

I refactor my reply model with eager loading like below:

...
protected $with = ['owner','favorites'];

 public function favorites(){
        return $this->morphMany('App\Favorite','favorited');
    }

 public function isFavorited(){

        return !! $this->favorites->where('user_id',auth()->id())->count();
    }

In my view:

 {{$reply->favorites_count}}

favorites_count return null. It was working fine before I add $with.

What did i do wrong?

Activity icon

Replied to Php Artisan Config:cache Removes All Tables

@sinnbeck Thanks, but i can assure you I didn't use RefreshDatabase trait, I only used DatabaseMigrations trait.

Activity icon

Replied to Php Artisan Config:cache Removes All Tables

@geordiejackson I am using the DatabaseMigration trait in my tests.

Activity icon

Replied to Php Artisan Config:cache Removes All Tables

@sinnbeck Okay it makes sense. So avoid caching config when using phpunit.

But it's still odd that it removes the actual tables from my database though.

Activity icon

Replied to Php Artisan Config:cache Removes All Tables

@sinnbeck How come running config:clear will make it work again?

  1. I am using mysql workbench for database. For testing, I configured a local test on my configuration.

  2. It removes all the tables of migration that I have created so I am not too sure.

  3. It happens when i run config:cache and I noticed the tables in my db are all missing. Running the vendor/bin/phpunit then removes it again.

Activity icon

Replied to Php Artisan Config:cache Removes All Tables

@sinnbeck I experimented it and it did remove it, why does it do that?

Activity icon

Started a new Conversation Php Artisan Config:cache Removes All Tables

I am running unit tests and all the tests passed but when I run php artisan config:cache, running the test again makes most of my test failed and I checked my database, the tables were gone.

Why does this happen and how do I fix this?

Tried to run php artisan migrate and run the phpunit test again and the tables are removed again.

Aug
10
2 months ago
Activity icon

Replied to WantsJson Does Not Exist.

Nvm the error is :

Error: Call to a member function assertSeeInOrder() on array.

Activity icon

Replied to WantsJson Does Not Exist.

@michaloravec It shows this error:

TypeError: Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null.

My browser returns the popularity correctly but the test case shows red with the error above.

Activity icon

Started a new Conversation WantsJson Does Not Exist.

I wrote a test to filter my threads based on popularity:

 /** @test */
    function a_user_can_filter_threads_by_popularity(){
        $this->withoutExceptionHandling();
        // Given we have three threads with 3 replies, 2 replies and 0 reply
        $threadWithThreeReplies = factory('App\Thread')->create();

        factory('App\Reply')->create(['thread_id' => $threadWithThreeReplies->id],3);

        $threadWithTwoReplies = factory('App\Thread')->create();
        factory('App\Reply')->create(['thread_id' => $threadWithTwoReplies->id],2);

        $threadWithNoReplies = $this->thread;

        //We should be able to fetch the threads page by popularity

        $response= $this->getJson('threads?popular=1')->json();

        //Return threads with most replies to least reply.
        $response->assertSeeInOrder([
            $threadWithThreeReplies->title,
            $threadWithTwoReplies->title,
            $threadWithNoReplies->title
            ]);

    }

And in my controller, I handle the response using wantJson() helper like below:

  public function index(Channel $channel, ThreadFilters $filters)
    {

        $threads = Thread::latest()->filter($filters);
        if($channel->exists){
            $threads->where('channel_id',$channel->id);
        }

        if(request()->wantsJson()){
            return $threads;
        }
         
        $threads = $threads->get();
        
        return view('threads.index',compact('threads'));
    }

Running the test says wantJson() does not exist, i'm guessing because the older laravel version has this method as I am watching a tutorial from laracast using this method. Are there any other alternatives to this?

Activity icon

Commented on A User Can Filter Threads By Popularity

It doesn't work for me and i'm using laravel 7 as well. The difference is I didn't use helper method for create()

Activity icon

Replied to Reference Relationship With Bracket And Without

i guess

$thread->replies()->get()

should be declared in the controller and just passed it as one to the view?

Activity icon

Replied to Adding A Global Scope To Count

@bugsysha Okay so if i were to have a relationship called creator() and would do the same like:

$builder->withCount('creator');

And access it like

$thread->creator_count

?

Activity icon

Replied to Adding A Global Scope To Count

@martinbean

I tried accessing it via

{{ $thread->replyCount()->replies_count }}

saying replyCount() is an undefined method.

i think replyCount is redundant and removing it and accessing like your third point:

{{ $thread->replies_count }}

will work.

Also,

class Thread extends Model
{
    protected $withCounts = ['replies'];
}

Does the variable need to be $withCounts or any other name?

Activity icon

Replied to Adding A Global Scope To Count

@bugsysha So "replyCount" is just the reference key of the global scope and

$builder->withCount('whatevername);

should be called like

$thread->whatevername_count

?

Activity icon

Started a new Conversation Adding A Global Scope To Count

I have a thread model and each thread has many relationship for replies. I added a global scope to my model so I can call it anywhere.

Thread model:

  protected static function boot(){
        parent::boot();

        static::addGlobalScope('replyCount',function ($builder){
            $builder->withCount('replies');
        });
    }

 public function replies(){
        return $this->hasMany('App\Reply');
    }

So when I try to retrieve the count in my blade like below:

This thread has {{$thread->replyCount} comments

it returns null. Was wondering, am I calling my scope wrongly?

Activity icon

Replied to Reference Relationship With Bracket And Without

So if I use

foreach($thread->replies() as $reply)
......

It would return nothing as it is a query builder ?

Activity icon

Replied to Reference Relationship With Bracket And Without

@sinnbeck Thanks for reply.

But with getting the creator name like

{{$thread->creator()->name}}

Don't I need to go into the database to retrieve the name of the thread creator?

That's what I am confused.

Activity icon

Started a new Conversation Reference Relationship With Bracket And Without

I am trying to reference a relationship for my threads that I created with creator and replies.

I found out that these two ways will work and fetch the correct value:

{{$thread->replies()->count()}}

or 

{{$thread->replies->count()}}

In another instance, say I want to find the name of the poster, I could do this:

{{$thread->creator->name}}

but this wouldn't work:

{{$thread->creator()->name}}

My thread model:

public function replies(){
        return $this->hasMany('App\Reply');
    }

 public function creator(){
        return $this->belongsTo('App\User','user_id');
    }

Why is this the case and when do I use bracket or without bracket to avoid confusion?

Aug
08
2 months ago
Activity icon

Commented on A Lesson In Refactoring

Same here, it was so simple to understand until this lesson where he starts the refactoring where it looks overkill and sooooo confused.... I have no idea if I should continue lol.

Aug
05
2 months ago
Activity icon

Replied to Failed Asserting That Exception Of Type "Illuminate\Auth\AuthenticationException" Is Thrown.

@martinbean You told me to use the act -arrange -assert pattern. What if I wish to redirect to a different route,say register page?

Will that still be a valid test case?

Activity icon

Replied to Failed Asserting That Exception Of Type "Illuminate\Auth\AuthenticationException" Is Thrown.

@sinnbeck But isn't this the wrong way?

Thought $this->expectExpection() should does the work, how come it does not work?

Activity icon

Replied to Failed Asserting That Exception Of Type "Illuminate\Auth\AuthenticationException" Is Thrown.

@sinnbeck Still throws the same error.

If I add this then it will work:

 $this->withoutExceptionHandling();
         $this->expectException(AuthenticationException::class);
Activity icon

Started a new Conversation Failed Asserting That Exception Of Type "Illuminate\Auth\AuthenticationException" Is Thrown.

I wrote a test case for unauthentication user so I will obviously expect the auth exception to be thrown but it was handled with this code below:

 public function unauthenticated_users_may_not_add_reply(){
        
         $this->expectException('Illuminate\Auth\AuthenticationException');
    
         $this->post('/threads/some-channel/1/replies', []);
        
        //$response->assertRedirect(route('login'));
       
    }

However, it still throws the same error. How do I handle this?

Aug
04
2 months ago
Activity icon

Replied to Factory Is Not Generating A Channel_id

@geordiejackson Okay i already solved it after banging my head few times.

Activity icon

Replied to Factory Is Not Generating A Channel_id

@geordiejackson Yea did check my imports.

This is my Channel migration (which appears fine):

    public function up()
    {
        Schema::create('channels', function (Blueprint $table) {
            $table->id();
            $table->string('name',50);
            $table->string('slug',50);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('channels');
    }