thomaskim

thomaskim

Member Since 4 Years Ago

Los Angeles

Experience Points 185,660
Experience Level 38

4,340 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 440
Lessons
Completed
Best Reply Awards 307
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

16 Nov
4 months ago

thomaskim left a reply on Illegal Operator And Value Combination.

@viernes If you make a form and pass an input value, then your code should work fine.

However, in the instance that you don't, then my example provides a fallback solution. In other words, a default value will only be set if you don't pass anything / if there is no value. If you do provide a value through a form or something else, then it will use that value instead.

14 Nov
4 months ago

thomaskim left a reply on Illegal Operator And Value Combination.

@Viernes You need to think about this from a logic / lifecycle standpoint. There's actually several things to go over, but I don't want to bombard you with a bunch of information. First think about the lifecycle.

The route hits the controller before the view. Route -> Controller -> View.

You set the priceValue input value in the view, which comes after the controller, right? So how is the controller (which comes before the view) supposed to know the value if you didn't set it yet? It doesn't know that yet unless you passed the value, which you didn't.

Therefore, one solution is to set a default value like I posted earlier.

thomaskim left a reply on Illegal Operator And Value Combination.

You end up passing a null value so in other words, this is most likely what's happening:

return $query->where('price','>=', null);

That doesn't work. It looks like you want to set a default value of 100 so you should be able to achieve that by passing in a default value like this:

public function index()
{
    return view('welcome')->with('projects',Project::price(Input::get('priceValue', 100))->get());
}
13 Nov
4 months ago

thomaskim left a reply on How To Return Relationship With Created Record

Do you mean something like this?

return response($user->load('roles'), 200);
12 Nov
4 months ago

thomaskim left a reply on Jeffery Ways "Favorite This"

Did you finish the video? He specifically went over the undefined variable $favorites issue in it. He temporarily assigns and passes the $favorites variable. Then, he later extracts it to a view composer.

https://laracasts.com/lessons/favorites-part-2

Also, this is a Laravel 4 tutorial, so things have changed. Regarding view composers, you can take a look at the docs here: https://laravel.com/docs/5.7/views#view-composers

thomaskim left a reply on Laravel Where('user_id') Seems Completely Ignored

@click already posted the solution. Have you tried his piece of code?

From a logic standpoint, it sounds like you always want to filter by the user's id while searching for either the name or ringnumber. So click's answer (with a link to the docs explaining why) should work.

thomaskim left a reply on Weird Issue With UpdateOrCreate

Someone else may have a simple solution to using composite keys, but as far as I know, it is just easier to add a primary key of id.

Also, I don't think your code works locally. It most likely works when creating a model, but not when you are updating. This is because a Pivot class is just an extension of the Model class, which expects a primary key of id.

As a result, when you do updateOrCreate, creating works fine because it is simply inputting the data into the table. Updating throws you that error because it's trying to fetch the row by id.

08 Nov
4 months ago

thomaskim left a reply on Middleware Not Working

@glasstream2000 Changing middleware to lowercase in your route group folder is in no way related to the capitalization of the Middleware folder. If it's causing a new error, then you need to start debugging the new error message.

07 Nov
4 months ago

thomaskim left a reply on Middleware Not Working

I believe this section is most likely the problem:

Route::group(['Middleware' => ['auth', 'isAdmin']], function()

The "Middleware" should be "middleware".

01 Nov
4 months ago

thomaskim left a reply on Laravel-5.6 Error: Creating Default Object From Empty Value

You're getting this error because a tag with that $id doesn't exist. You will probably get null when you dump out the tag like this:

$tag = Tag::find($id);
dd($tag);

One solution is throw an exception when the tag doesn't exist like so:

$tag = Tag::findOrFail($id);

Another solution would be to check if the tag exists manually and then return with a message saying that the tag doesn't exist:

$tag = Tag::find($id);

if (is_null($tag))
{
    // return back with message saying that tag doesn't exist
}

$tag->tag = $request->tag;

$tag->save();

Session::flash('success', 'Tag Updated Successfully.');

return redirect()->route('tags');

If you know for sure that the tag does exist, then you need to figure out why the code isn't fetching it. You might be using the wrong $id so try checking your view or your routes or anything along those lines.

29 Oct
4 months ago

thomaskim left a reply on Missing Required Parameters For [Route: ... ] [URI: ... ]

@leux76 The apostrophe appears here:

data-href="{{ route('cart-update', $item->slug) }}'"

At the very end, you have an apostrophe before the closing quotation mark. Anyway, regarding your problem, this is your route:

Route::get('cart/update/{product}/{quantity}', [
    'as' => 'cart-update',
    'uses' => '[email protected]'
]); 

As you can see, it's expecting two parameters - product and quantity. However, in your cart.blade.phpfile, you have this:

data-href="{{ route('cart-update', $item->slug) }}"

You are only passing the slug without the quantity. As a result, Laravel throws an error. You can fix this by passing an array of parameters like this:

data-href="{{ route('cart-update', [$item->slug, $item->quantity]) }}"
25 Oct
4 months ago

thomaskim left a reply on FindOrFail Returns Incorrect Value

@boldstar Your original code is causing issues because of this line:

$user = User::findOrFail($request->assigned_to)->value('name');

The value() method is not a model behavior. It's a query behavior. So essentially, in the original code, by doing this:

->value('name')

You are doing:

select `name` from `users` limit 1

In other words, you are simply fetching the first user, and assigning that object to the $user variable. What you most likely wanted to do was simply this:

$user = User::findOrFail($request->assigned_to)->name;

This fetches the user by the id and then returns the name. However, your new updated code is better since it doesn't fetch the entire user data. It only fetches and returns the user's name.

24 Oct
4 months ago

thomaskim left a reply on Get AVG From HasMany Relation Field?

Your code should work. The only reason I could think of as to why it's returning null is that the model has no reviews. Maybe return a certain value if it has no reviews. Something like this:

public function getRatingAttribute()
{
    return $this->reviews()->avg('rating') ?: 0;
}

thomaskim left a reply on Update User Status After 6 Month Or More

You can also just not bother updating it until the user is actually using your site.

  1. Person A's subscription ends.
  2. Person A goes to your site.
  3. Check Person A's subscription end date.
  4. If the subscription has ended, update status to basic.
19 Oct
4 months ago

thomaskim left a reply on Laravel Is Trying To Update _method Field

@nnnayeem If the user and vendor have a one-to-one relationship, you can just do this:

$user->vendor->update($data);

That should work fine. This fetches the user's vendor and returns the actual Vendor model instance. Then when you call update($data) on it, Laravel can now properly filter out nonfillable fields.

You can dd $user->vendor() and $user->vendor to see the differences between the two. :)

thomaskim left a reply on Laravel Is Trying To Update _method Field

In this part of the code:

$user->update($data);
$user->vendor()->update($data);

You're probably wondering why the $user updates properly but not the vendor. You added the $fillable fields so what's the problem? It's simple. The fillable field only works for a model, right? So, for the $user, you fetched an actual instance of the user model. Then when you update it, it knows which fields are fillable and as a result, it works.

You didn't do the same for the vendor.

Your error comes up when trying to update the vendor. There is no vendor model. You never fetched a vendor, and quite frankly, I'm not even sure how you are trying to update it. Are there multiple vendors, and you are trying to update all vendors that belongs to this user? Can a user only have one vendor? We don't know the relationship, but because there is no actual vendor model, the fillable fields are never used to remove excess fields during the update.

28 Jun
8 months ago

thomaskim left a reply on Adding Background-image Using Sass Laravel 5.5

You can use absolute URLs instead of relative ones to get around this issue. If not, try adding this to your webpack.mix.js file.

mix.options({ processCssUrls: false });
24 Jan
1 year ago

thomaskim left a reply on Why Is This Not Taking Up The Full Width Of The Container? [Bootstrap 4]

Because col-8 will take up 2/3 of the width. You could use col instead of col-8 and col-4?

https://codepen.io/anon/pen/mpYvbM

18 Jan
1 year ago

thomaskim left a reply on Laravel Observer Not Adding Deleted_by (Soft Delete)

@wamae This is an issue with using observers and softDeletes right now because the softDeletes trait doesn't update "dirty" attributes.

This exact issue was brought up before but there are no plans on changing this right now. You can check out the issue brought up here: https://github.com/laravel/framework/pull/18119

So, at the moment, you can run save on the model as @wilk_randall suggested, but that would run two queries.

17 Jan
1 year ago

thomaskim left a reply on Laravel 5.5 Return Back To Registration Form If Conditions Is Not Met

@mindtaker

The create method should not or try to redirect a user. If you look at the doc blocks, you will see that it should return an instance of the user so trying to do a return redirect won't work.

If you want to make sure that the email exists in the database, all you need to do is alter the default validator method to this:

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|exists:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

As you can see, for email, you are now validating that it exists in the users table. I'm not sure why you would do that, but since registrations should be for non-existing users, but anyway, not really going to question the why. Just that, you should do the validation in the validator method.

thomaskim left a reply on Route Not Defined For Logout

@dokunbam Which part do you want explained?

The name method does the same thing as the as array key. In other words, you have this right now:

Route::get('dashboard', [
        'uses' => '[email protected]',
        'as'   => 'dashboard'
    ])->middleware('auth');

Another way to define that is to do this:

Route::get('dashboard', '[email protected]')->name('dashboard')->middleware('auth');

It does the exact same thing. Just two different ways to approach it. For the first one, you define the name using the as array key. For the second, you define the name using the name method.

thomaskim left a reply on Problem With Returning A Foreach Loop From Laravel Controller To Blade View

foreach($cong as $gemeente)
{
    ....
    $data = $data->incomingStreams;
    ...
}

On each loop, aren't you just erasing the previous $data and overriding it to be the latest incoming stream? Is it possible that the last incoming stream is just an empty array?

thomaskim left a reply on 5.2 To 5.5. GetRegister() Method Is Gone. What Now?

Yes, you can see that in 5.2, the getRegister method just called the showRegistrationForm. There was no longer any point in having the getRegister method since it just delegated to the showRegistrationForm method.

thomaskim left a reply on 5.2 To 5.5. GetRegister() Method Is Gone. What Now?

Take a look inside the RegistersUsers trait. You will see that the getRegister method is now called showRegistrationForm.

thomaskim left a reply on Route Not Defined For Logout

In addition to having the logout route defined twice, there is also this problem:

return redirect()->route('login');

You are redirecting to the route named login, but it doesn't exist. You actually didn't assign a named route to login so change your login route to this:

Route::get('/login', function(){
    return view('home');
})->name('login');
16 Jan
1 year ago

thomaskim left a reply on Need Clarification On Query Strings With Laravel

Typically, any required parameters would be in the path. Any optional parameters (like filters) are query strings.

So, most people use query strings for paginations, sorting, filtering, searches, etc.

thomaskim left a reply on 5.2 To 5.5 Auth Doesn't Work Anymore.

So you're submitting a username field instead of email?

Just add this to your controller then to override the default username() method:

public function username()
{
    return 'username';
}

thomaskim left a reply on Javascript For PHP Developer

Yep, and it's on this site. Jeffrey has his own series on Vue.js.

https://laracasts.com/series/learn-vue-2-step-by-step

07 Dec
1 year ago

thomaskim left a reply on Route Syntax/semantics Opinion

Personally, I prefer the first option. I think it looks cleaner and is easier to understand.

Ultimately though, it doesn't matter. Just go with the option that you like.

05 Dec
1 year ago

thomaskim left a reply on Eloquent Insanity

Page::with('pageitems')->where('token', $token)->get();

You are fetching all pages with the matching token. Then, it appends each page's items to the corresponding page. So while you are getting the page items, they are the child of the parent page.

So, it should be more along the lines of this:

// Renamed the variable to "pages" (more appropriate)
$pages = Page::with('pageitems')->where('token', $token)->get();

Then in your view:

// Loop through the pages
@foreach ($pages as $page)
    // Loop through each page's items
    @foreach ($page->pageitems as $item)
        // Echo out the item name
        {{ $item->item_name ]}
    @endforeach
@endforeach
04 Dec
1 year ago

thomaskim left a reply on How Can I Add A Column Via Migration Without Having To Drop The Table?

You're not supposed to add it to the old migration file. You need to create a new migration file, and then add the corresponding code:

// This gets the users table and adds an email column
Schema::table('users', function (Blueprint $table) {
    $table->string('email');
});

Changes you make to the database should be a new migration file. If you come back in the future and want to alter a column or add another table, that needs to be another migration file. If you decide to drop a table because it's no longer needed, then that needs to be another migration file. Think of each migration as sort of like a snapshot of what your database looked like during that time.

Migrations are like version control for your database, allowing your team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you've faced the problem that database migrations solve.

21 Nov
1 year ago

thomaskim left a reply on Why Use WithCount() Over Just With()?

@BryceSharp I don't think that's correct. I'm almost positive that withCount should be running a subquery to get the count. It shouldn't call the with() method.

@JeffBeltran Are you absolutely certain that the second query is only 350ms? Your second query runs 2 separate queries whereas the first runs a subquery inside a single query.

In addition, what are you trying to achieve? In your first example (withCount), you can access the number of enrollments easily because it will be appended as an attribute of the parent. Very simple and efficient if all you want is the number of enrollments. However, if you are also trying to get other attributes that belong to enrollment, you want the with method and may accidentally be running more queries by trying to access enrollments.

In your second example (with), you can also access the number of enrollments, but you are fetching the entire "enrollment" model. You are getting a collection of these and then essentially appending each enrollment model to its respective parent. You will have access to all enrollment attributes. In addition to this, in order to get the enrollment count, you will need to run the count() method on the collection instance. You are doing a lot more to have access to a lot more data.

20 Nov
1 year ago

thomaskim left a reply on Use Timestamp As Primary Key

Using a timestamp as your primary key is a terrible idea. Life is just much easier to use the standard auto incrementing integer as your primary key, especially since there is no guarantee that two timestamps are absolutely unique from one another.

So, I would suggest auto incrementing your id, and then just having a "created_at" timestamp.

Next, you are getting this error because by default, Laravel expects your primary key to be auto incrementing. If for some reason, you are not doing this, you need to put this in your model:

public $incrementing = false;
17 Nov
1 year ago

thomaskim left a reply on Missing Fields When Using Create()

@kevbrn I'm not sure what's going on in your other controller (what you are passing, what the model is, etc.), but it doesn't make sense to do what you are doing. I'm certain that it isn't working as you are intending.

Also, know that Input::all() and request()->all() do and return literally the exact same thing. You should be using one or the other. They both ultimately delegate to the all() method inside Illuminate\Http\Concerns\InteractsWithInput.

thomaskim left a reply on Missing Fields When Using Create()

Either use Input::all() or request()->all().

You don't do request(Input::all()).

23 Oct
1 year ago

thomaskim left a reply on Use Of Undefined Constant Message

Laravel's Blade engine is trying to echo out message. If you want to use Vue's curly braces instead, prepend it with the @ symbol.

@{{ message }} 

Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Blade rendering engine an expression should remain untouched. For example:

https://laravel.com/docs/5.5/blade

18 Sep
1 year ago

thomaskim left a reply on Not Generating The Key In .env

If you are running an older version of composer, then the Laravel installation will not generate the .env file.

Try upgrading composer.

composer self-update

thomaskim left a reply on MODEL->save() Error

I think the main problem is that he's overriding the getAttributes method. This breaks several internal methods inside Laravel.

I would rename getAttributes() to something else like getDocumentAttributes().

thomaskim left a reply on Using Route Model Binding Without Global Scope

I think what Chris is asking is how to remove global scopes for just that one route, not for all routes.

What you can do is change the parameter name in your web file for that one route.

Route::get('users/{any_user}', '[email protected]');

Note the any_user. Change that to whatever naming convention you find most convenient.

Then, in your RouteServiceProvider, change yourboot` method to something like this:

    public function boot()
    {
        parent::boot();

        Route::bind('any_user', function($id) {
            return \App\User::withoutGlobalScopes()->findOrFail($id);
        });
    }

Match the any_user parameter name, and you can customize that logic.

16 Sep
1 year ago

thomaskim left a reply on For Many-to-Many Relationship - Why Is There No Integrity Violation When Timestamps Are Missing?

MySQL made some changes in 5.7 that caused a lot of issues for people. Because of this, Laravel's timestamps() method was changed to default to nullable timestamps. In other words, when you do this:

$table->timestamps();

You are by default creating nullable timestamps as can be seen in the code here:

https://github.com/laravel/framework/blob/5.5/src/Illuminate/Database/Schema/Blueprint.php#L839

If you go to an older codebase for Laravel, you can see that this didn't used to be the case. For example: https://github.com/laravel/framework/blob/e35c7ab0c3e29f93e8e0ac53d041f93d8a5b21dd/src/Illuminate/Database/Schema/Blueprint.php#L792

thomaskim left a reply on Syntax Error Or Access Violation 1064 Issue

I'm guessing your version of MariaDB probably doesn't support json. I'm not sure if MariaDB supports json yet or not.

A workaround is to use text instead of json.

 $table->text('permissions')->default('{}');

You can then cast it as json on your model by adding this:

    protected $casts = [
        'permissions' => 'json',
    ];
14 Sep
1 year ago

thomaskim left a reply on Route::delete Not Working

You need to drop the $ and change your route to this:

Route::delete('fields/{field}', function($field) { return 'hi';})->name('fields.delete');

thomaskim left a reply on InvalidArgumentException With Message 'Trailing Data' For A Date Field

If you can't modify your database, you can add this to your model:

    protected function getDateFormat()
    {
        return 'Y-m-d H:i:s.u';
    }

But, since this will affect all your models, I think it would be best to create a base model with this method and then have all your models extend this base class instead.

11 Sep
1 year ago

thomaskim left a reply on Is It Possible To Shuffle Lazy Loading Collection?

There are multiple ways to achieve this. You can specify it when you define the relation. For example, in your Stack model:

public function questions()
{
    return $this->hasMany(Question::class)->inRandomOrder();
}

Now, when you load the relationship, it will automatically randomize the order. Or you can define a new relationship with a better name.

public function questionsInRandomOrder()
{
    return $this->hasMany(Question::class)->inRandomOrder();
}

Then, you can do this:

$stack->load('questionsInRandomOrder.choice');

Naturally, you can also do this with the relationship between Question and its Choices.

thomaskim left a reply on Method Spoofing Is Not Working Laravel 5.4

The problem is here:

$tenant = Tenant::where('user_id', $id);
$tenant->update(request()->all());

When you do $tenant = Tenant::where('user_id', $id);, you are getting an eloquent builder instance. You are not getting a model instance. This bypasses the fillable attribute. What you want to do is fetch the model first. Then when you call update, you will do so on the model instance.

In other words, something like this:

$tenant = Tenant::where('user_id', $id)->first();
$tenant->update(request()->all());
07 Sep
1 year ago

thomaskim left a reply on How Do I Display The Value Of Count() Inside Blade View?

Are you passing the variable to your blade view?

$pendingMembers = Member::where('status', '=', null)->get();

return view('SOME_BLADE_VIEW', [
    'pendingMembers' => $pendingMembers
]);

https://laravel.com/docs/5.4/controllers#basic-controllers

05 Sep
1 year ago

thomaskim left a reply on What $table->foreign~ On A Migration Does?

They are different things. Basically, what foreign key constraints do is let your database maintain the integrity of your data. It'll be easier to understand with an example.

Lets say you have a state. A state has many cities. In other words, a city belongs to a state. In the city table, you have a state_id.

What happens if you add a city with a state_id that doesn't exist?

Without the foreign key constraint, your database will not throw an error. With the foreign key constraint, your database knows about the relationship and will throw an error. In other words:

$table->integer('state_id')->unsigned(); // This simply creates an unsigned integer column
$table->foreign('state_id')->references('id')->on('states'); // This ensures that the state_id must be a valid / existing one

You'll also see cascading. Something like this:

$table->foreign('state_id')->references('id')->on('states')->onDelete('cascade');

What this ensures is that if a state is deleted, all its corresponding cities will also be deleted as well.

thomaskim left a reply on Inverse One-to-Many Relationship NULL

It always helps to give real-life concrete examples rather than theoretical examples. Hard to follow what's going on sometimes with these "A" and "B" classes.

One thing that can be changed is providing the fully qualified class name resolution:

public function B()
{
    return $this->belongsTo('App\B');
}

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

Or changing it into B::class and A::class.

02 Sep
1 year ago

thomaskim left a reply on Eloquent - Advanced Where Clauses

$orders = Order:all();

This already queries the database and returns a collection. Try something like this instead:

$now = Carbon::now();

$orders = Order::where('status', '<', 8)
    ->where(function($q) use ($now) {
        $q->where(function($query) use ($now) {
            $query->where('status', '<>', 3)
                ->where('completion_date', '<', $now);
        })
        ->orWhere(function($query) use ($now) {
            $query->where('status', 3)
                ->where('production_date', '<', $now);
        });
    })
    ->get();
01 Sep
1 year ago

thomaskim left a reply on Conditional Routing (redirect->action() Throwing Error)(updated)

However this does not answer, my original question, why does the original return that controller is note defined when it is and functionally works

It does not say that the controller is not defined. It says that the action is not defined. How is Laravel supposed to redirect to a URL if you don't define the URL associated with the action?