thomaskim

Experience

185,150

326 Best Reply Awards

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

18th September, 2017

thomaskim left a reply on Not Generating The Key In .env • 3 days 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 • 3 days 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 • 3 days 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}', 'SomeController@reactivate');

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? • 5 days 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 • 5 days 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 • 1 week 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 • 1 week 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? • 1 week 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 • 1 week 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 weeks 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 weeks 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 weeks 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 weeks 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 weeks 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 • 3 weeks 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? • 3 weeks 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? • 3 weeks 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. • 3 weeks 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 • 3 weeks 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 • 3 weeks 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 • 3 weeks 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' => 'RoomsController@update',
  '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? • 4 weeks 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? • 1 month 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 • 1 month 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 • 1 month 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 • 1 month 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 • 1 month 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() • 1 month 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 • 1 month 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() • 1 month 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 • 1 month 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 • 1 month 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 • 1 month 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','RecordsController@temprorary');

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 • 1 month 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 • 1 month 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 • 1 month 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 • 1 month 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 • 1 month 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 • 1 month 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 • 1 month 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}', 'PagesController@story')->name('story');

7th August, 2017

thomaskim left a reply on Parse Syntax Error (interesting A Error) • 1 month 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) • 1 month 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 • 1 month 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 • 1 month 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" • 1 month 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();
});

thomaskim left a reply on Passing Email 'from' Variable To Markdown Build() Function? • 1 month ago

@idcreatv

Maybe I'm not understanding the question, but since you passed the values in the constructor, couldn't you just do this?

return $this->markdown('emails.customer-quote')->subject($subject . ' ' . $rand)->from($this->author_email, $this->author_name);

2nd August, 2017

thomaskim left a reply on Getting The $to Data Inside The Mailable • 1 month ago

@nam_co You don't need to add a public $to property at the top. Also, it's not set in the _construct() method so try saving it in the build() method.

thomaskim left a reply on Count Result Based On Specific Value • 1 month ago

@ozmnow You can probably do something like this:

$events = EventHistory::where('u_h_id', $id)
                    ->where('has_read', 0)
                    ->groupBy('event_type')
                    ->get(['event_type', DB::raw('count(*) as total')]);

foreach ($events as $event) {
    // $event->event_type to get the type
    // $event->total to get the amount
}

1st August, 2017

thomaskim left a reply on Getting The $to Data Inside The Mailable • 1 month ago

@nam_co The Mailable class already has the $to property.

You can access it by calling $this->to, but it's not yet available in the constructor because it hasn't been set yet.

You can access it in the build method if necessary.

31st July, 2017

thomaskim left a reply on Should Cache::put() Return A Value? • 1 month ago

What value would it return and what would be the purpose of it?

It's for storing something in the cache. You provide the key, value, and duration.

Anything that it returns should be values you already have.

Edit Your Profile
Update

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