thomaskim

Experience

187,300

326 Best Reply Awards

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

21st November, 2017

thomaskim left a reply on Why Use WithCount() Over Just With()? • 3 days 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 • 4 days 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() • 1 week 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() • 1 week 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 • 1 month 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:

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

18th September, 2017

thomaskim left a reply on Not Generating The Key In .env • 2 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 • 2 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 • 2 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()
    {
        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.

16th September, 2017

thomaskim left a reply on For Many-to-Many Relationship - Why Is There No Integrity Violation When Timestamps Are Missing? • 2 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:

$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 • 2 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.

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

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 • 2 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 • 2 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? • 2 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:

$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 • 2 months ago

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

7th September, 2017

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

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

5th September, 2017

thomaskim left a reply on What $table->foreign~ On A Migration Does? • 2 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:

$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 • 2 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 • 2 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);
        });
    })
    ->get();

1st September, 2017

thomaskim left a reply on Conditional Routing (redirect->action() Throwing Error)(updated) • 2 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 • 2 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? • 2 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? • 2 months ago

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

https://github.com/laravel/framework/issues/20843

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

This part of your code:

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

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

@almost_pitt

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;
    $rooms->save();

    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;
    $rooms->save();

    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? • 3 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? • 3 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()
{
    parent::boot();

        static::updating(function($model) {
        if ($model->isDirty('column_3'))
        {
            $model->column_1++;
        }
    });
}

18th August, 2017

thomaskim left a reply on Change Password Not Work • 3 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 • 3 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 • 3 months ago

@phpguru

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 • 3 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() • 3 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.

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Relations/Relation.php

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

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

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

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.
$boat->fill($request->except('avatar'));

// 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/' ;
    $file->move($destinationPath,$fileName);
    $boat->avatar = $fileName ;
}

// Then we just save
$boat->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() • 3 months ago

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

You can see the method here: https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#L733

The save method only exists on the model instance.

17th August, 2017

thomaskim left a reply on Items And Groups • 3 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 : '' }}

thomaskim left a reply on Php Artisan Migrate:refresh Error • 3 months ago

You have a typo in one of your migration files.

"chema" should be "Schema".

15th August, 2017

thomaskim left a reply on TokenMismatchException After Page Refresh • 3 months ago

Without seeing some code, I'm going to guess that you are returning a view from your POST route.

After you submit a form, you shouldn't return a view. You should redirect to another route that returns a view. In other words, this route:

Route::post('/temprorary/show','[email protected]');

Should not return a view. It should redirect to another route that returns a view.

14th August, 2017

thomaskim left a reply on Change Request Input Before Validation • 3 months ago

@kgp43 If you personally find this method the simplest way of doing things, then I think it's fine. There's no "wrong" way of doing it or a smarter way. And, down the line, you may change your style of coding. When that happens, you can change things up.

But, if you add the middleware to the protected $middleware array, it will be running on every single request automatically. I'm not sure if that was your intention. If you only want to run on specific routes / requests, then you can remove it from the $middleware array and then specify when you want to use it (like in your controller).

thomaskim left a reply on Ck Editor • 3 months ago

You don't set a value attribute for a textarea. It's set in between the tags so try this instead:

<textarea name="details" rows="8" cols="80" class="form-control">{{ $item->details }}</textarea>

thomaskim left a reply on Change Request Input Before Validation • 3 months ago

@kgp43 You want to use the merge method.

$request->merge([
    'cvr' => str_replace(' ', '', $request->cvr)
]);

If you want to remove all whitespace and not just spaces, you can do this instead:

$request->merge([
    'cvr' => preg_replace('/\s+/', '', $request->cvr)
]);

10th August, 2017

thomaskim left a reply on Custom Directive Values • 3 months ago

@topvillas Try using the with() helper method.

Blade::directive('date', function ($expression) {
    $expression = with($expression);
    $formatted = Carbon::parse($expression)->format("m-d-Y");
    return "<?php echo $formatted; ?>";
});

Remember to run php artisan view:clear after making these changes.

Also, you can inline it:

Blade::directive('date', function ($expression) {
    return "<?php echo \Carbon\Carbon::parse(with($expression))->format('m-d-Y'); ?>";
});

While we're at it, if it's inlined, you may not need the with method.

Blade::directive('date', function ($expression) {
    return "<?php echo \Carbon\Carbon::parse($expression)->format('m-d-Y'); ?>";
});

9th August, 2017

thomaskim left a reply on Routing Issues • 3 months ago

@jbowman99 In your config/app.php file, you can switch the order of the service providers around.

So put the Backpack service provider Backpack\Base\BaseServiceProvider::class, right before App\Providers\RouteServiceProvider::class,.

8th August, 2017

thomaskim left a reply on Problems With Laravel Explicit Binding • 3 months ago

Try changing this: Route::model('user', App\User::class);

To this: Route::model('user', \App\User::class);

Either that or import it at the top, and just do Route::model('user', User::class);

thomaskim left a reply on Routing Issues • 3 months ago

For catch-all routes like this one, you want to put it after / below the other routes so that the other routes take priority over it.

// Put this route before
Route::get('/admin/dashboard', ...);

// Then put this route after
Route::get('/{issue_title}/{story_title}', '[email protected]')->name('story');

7th August, 2017

thomaskim left a reply on Parse Syntax Error (interesting A Error) • 3 months ago

@ustabasiibrahim list is one of the reserved keywords you can't use in PHP:

http://www.php.net/manual/en/reserved.keywords.php

thomaskim left a reply on Parse Syntax Error (interesting A Error) • 3 months ago

@usa_com list is one of the reserved keywords you can't use in PHP:

http://www.php.net/manual/en/reserved.keywords.php

thomaskim left a reply on Fix For N + 1 Problem • 3 months ago

@mevlutozdemir That's weird. For as long as I can remember, eloquent collections have had the load method.

Can you check if it's an eloquent collection or support collection? Or, how you are setting the $shoppingCart variable?

4th August, 2017

thomaskim left a reply on Fix For N + 1 Problem • 3 months ago

@mevlutozdemir Instead of using each, you can call load directly on the collection. That should remove a lot of extra queries.

$shoppingCart->load([

            'product',

            'product.attribute',

            'product.images'
]);

thomaskim left a reply on Auth::routes() Inside Prefixed Group, Inside Cusom Package, Returns "Class Auth\LoginController Does Not Exist" • 3 months ago

@str In the original RouteServiceProvider, they also set the proper namespace. Maybe try something like this:

Route::group(['prefix' => 'admin', 'namespace' => 'App\Http\Controllers'], function () {
    Auth::routes();
});
Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.