333 Best Reply Awards

  • Member Since 3 Years Ago
  • 406 Lessons Completed
  • 2 Favorites

24th January, 2018

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

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

18th January, 2018

thomaskim left a reply on Laravel Observer Not Adding Deleted_by (Soft Delete) • 1 month ago

@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:

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

17th January, 2018

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


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 • 1 month ago

@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'

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 • 1 month ago

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? • 1 month ago

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? • 1 month ago

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 • 1 month ago

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');

16th January, 2018

thomaskim left a reply on Need Clarification On Query Strings With Laravel • 1 month ago

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. • 1 month ago

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 • 1 month ago

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

7th December, 2017

thomaskim left a reply on Route Syntax/semantics Opinion • 2 months ago

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.

5th December, 2017

thomaskim left a reply on Eloquent Insanity • 2 months ago

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 ]}

4th December, 2017

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

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) {

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.

21st November, 2017

thomaskim left a reply on Why Use WithCount() Over Just With()? • 2 months ago

@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.

20th November, 2017

thomaskim left a reply on Use Timestamp As Primary Key • 2 months ago

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;

17th November, 2017

thomaskim left a reply on Missing Fields When Using Create() • 3 months ago

@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() • 3 months ago

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

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

23rd October, 2017

thomaskim left a reply on Use Of Undefined Constant Message • 3 months ago

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:

18th September, 2017

thomaskim left a reply on Not Generating The Key In .env • 5 months ago

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 • 5 months ago

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 • 5 months ago

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()

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

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

16th September, 2017

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

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:


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

If you go to an older codebase for Laravel, you can see that this didn't used to be the case. For example:

thomaskim left a reply on Syntax Error Or Access Violation 1064 Issue • 5 months ago

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.


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

    protected $casts = [
        'permissions' => 'json',

14th September, 2017

thomaskim left a reply on Route::delete Not Working • 5 months ago

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 • 5 months ago

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.

11th September, 2017

thomaskim left a reply on Is It Possible To Shuffle Lazy Loading Collection? • 5 months ago

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:


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 • 5 months ago

The problem is here:

$tenant = Tenant::where('user_id', $id);

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();

7th September, 2017

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

Are you passing the variable to your blade view?

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

return view('SOME_BLADE_VIEW', [
    'pendingMembers' => $pendingMembers

5th September, 2017

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

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:


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 • 5 months ago

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.

2nd September, 2017

thomaskim left a reply on Eloquent - Advanced Where Clauses • 5 months ago

$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);

1st September, 2017

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

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?

31st August, 2017

thomaskim left a reply on Blank Page After Redirect • 5 months ago

@temi You are forgetting the return statement.

Change redirect('/'); to return redirect('/');

30th August, 2017

thomaskim left a reply on Relation Don't Deliver All Data Correctly By ::with('my_relation') Call? • 5 months ago

You need to provide more information. How did you set your relationship? What does the staff() method do? What does your database look like?

There's too little information to properly assess what's going on.

thomaskim left a reply on Laravel 5.5 Installation Seems To Be Missing .env? • 5 months ago

It properly created the env files for me as well. But according to this, try updating composer:

thomaskim left a reply on Update Form With Image Field. • 5 months ago

This part of your code:

if ($request->hasFile('images')) {
    $file = $request->file('images');
    $path = $request->photo->path()      

Shouldn't "images" be "image" like how you have it in your store method?

29th August, 2017

thomaskim left a reply on Error Call To A Member Function Path On Null • 5 months ago

You are most likely leaving off enctype="multipart/form-data". Your form should be something like this whenever you have an input file type:

<form method="POST" enctype="multipart/form-data" ...

28th August, 2017

thomaskim left a reply on Trying To Get Property Of Non-object - For Authorized Users Only • 5 months ago

Looks like there is no room with that slug.

Change first() to firstOrFail() and I'm guessing you'll get the ModelNotFoundException or the NotFoundHttpException.

25th August, 2017

thomaskim left a reply on (1/1) MethodNotAllowedHttpException - Update A Thread • 5 months ago


Several things that you need to fix.

  1. First, this is your form:
<form action="{{ route('rooms.update', ['slug' => $rooms->slug ])}}" method="post">
    {{ csrf_field() }}
    {{ method_field('PUT') }}

That is a put route. So like @JackJones said, you need to change your route to reflect that:

Route::put('room/update/{slug}', [
  'uses' => '[email protected]',
  'as' => 'rooms.update'
  1. Once that's fixed, you'll also notice that your route is accepting a $slug variable, but your method is accepting an $id variable. So you should change $id to $slug like so:
public function update(Request $request, $slug)
    $this->validate($request, [
        'type_of_accomodation' => 'required',
        'price' => 'required|numeric'

    $rooms = Room::find($id);
    $rooms->type_of_accomodation = $request->rooms;

    Session::flash('success', 'Room edited successfully');

    return redirect()->route('room', ['slug' => $room->slug]);
  1. With that change, your find method will be wrong because you need to find the room based on the slug (not id). So, you'll need to do something like this:
public function update(Request $request, $slug)
    $this->validate($request, [
        'type_of_accomodation' => 'required',
        'price' => 'required|numeric'

    $rooms = Room::where('slug', $slug)->first();
    $rooms->type_of_accomodation = $request->rooms;

    Session::flash('success', 'Room edited successfully');

    return redirect()->route('room', ['slug' => $room->slug]);

Also, I would probably change first() to firstOrFail().

22nd August, 2017

thomaskim left a reply on Is My Destroy Method Properly Protected? • 5 months ago

Your code suggests that anybody with an account can delete users.

You probably want to protect this action using roles / permissions.

19th August, 2017

thomaskim left a reply on Update A Value Only If A Specific Column Changes? • 5 months ago

I thought about events as well, but do you have the old and new value available? If so how to access it?

You'll probably need to adjust this a bit, but you can use the isDirty method to see if an attribute has changed from its original value. So something like this:

protected static function boot()

        static::updating(function($model) {
        if ($model->isDirty('column_3'))

18th August, 2017

thomaskim left a reply on Change Password Not Work • 6 months ago

@Andreas94 Yes, that is the issue. You are basically hashing the password, and then hashing it again. You need to remove one of them.

thomaskim left a reply on Change Password Not Work • 6 months ago

The pw generated in the DB is different from the tinker output. That's very weird.

Can you check your User file to see if you are accidentally hashing the password again? I've done that in the past. Lol.

I had a mutator in the User model that was hashing the password so manually calling bcrypt on the password made it so that my password was hashed twice.

thomaskim left a reply on L5.4 Accessors And Mutators On A Column With An Unders • 6 months ago


Your mutator should be like this:

public function setIpAddressAttribute($string)
    $this->attributes['ip_address'] = ip2long($string);

thomaskim left a reply on Change Password Not Work • 6 months ago

Password is fillable as shown in the default User class.

At the moment I tried to do the same as the guide, but the password that is generated and stored in db, does not work,

What does that mean? You're supposed to login with the password you provided. Not the hashed password so the password in the database is not the password you use to login.

thomaskim left a reply on Call To Undefined Method Illuminate\Database\Query\Builder::save() • 6 months ago

@bobbybouwmann I don't understand. What you linked to shows calling the save method on a hasOne or hasMany relationship.

There is no save method on the BelongsTo or its parent Relation classes.

thomaskim left a reply on Laravel 5.4 - Updating A File Record • 6 months ago

If I were to guess, it would be this part right here:

        $boat->avatar = $fileName ;
    $boat->save() ;
    $boat_update = $request->all();

You are setting the file name and saving it. But right after you do that, you are overwriting it with $request->all() and updating it. I would try this instead:

$boat = Boat::find($id);

// This is like $request->all except it doesn't set the avatar
// You "fill" the new data so that it doesn't call save yet.

// If there is a file, we set the avatar
if($file = $request->hasFile('avatar')) {
    $file = $request->file('avatar') ;
    $fileName = $file->getClientOriginalName() ;
    $destinationPath = public_path().'/img/boats/avatars/' ;
    $boat->avatar = $fileName ;

// Then we just save

$request->session()->flash('alert-success', 'Boat Successfully Updated!');
return redirect('/management');

thomaskim left a reply on Call To Undefined Method Illuminate\Database\Query\Builder::save() • 6 months ago

@birendragurung What you mean to use is the create method. Replace save with create.

You can see the method here:

The save method only exists on the model instance.

17th August, 2017

thomaskim left a reply on Items And Groups • 6 months ago

Does every item have to belong to a group? I'm guessing not all items actually belong to a group so the group_id is null.

Try changing this:

{{ $item->groups->name}}

to this:

{{ $item->groups ? $item->groups->name : '' }}
Edit Your Profile

Want to change your profile photo? We pull from