kfirba

Experience

203,855

113 Best Reply Awards

  • Member Since 2 Years Ago
  • 1152 Lessons Completed
  • 22 Favorites

10th October, 2017

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 1 week ago

@splendidkeen Glad I could help :)

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 1 week ago

@splendidkeen If I understand correctly, in your navigation code, you check for an authenticated partner and if there is one, you try to add some navigation links.

I think that within that context, the Auth::user() call is actually returning a Business model. Can you try changing this line:

{{  Auth::user()->business->getCompanyName() }}

To:

{{  Auth::user()->getCompanyName() }}

If it does not work, can you post here what does Auth::user() returns? You should be able to figure this out by calling:

get_class(Auth::user())

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 1 week ago

@splendidkeen I'm not sure what you are trying to do but calling Auth::user() will return the currently authenticated user for the given guard or the default guard defined in your config file.

I'm assuming that there is a Business model that has a user_id column.

On your User model (or any other model you use for authentication), you should have a business relationship:

class User extends Authenticatable
{
    // ...
    
    public function business()
    {
        return $this->hasOne(Business::class); 
    }
}

Now when you access the property business on Auth::user(), Laravel will detect that there is a business relationship defined and will automatically fetch that relationship for you.

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 1 week ago

@splendidkeen Hey.

Well, you can indeed check if the user is authenticated. However, it seems like your issue is not with the user not being authenticated but with your authenticated user not being associated with a business.

Since your error message indicate that you call getCompanyName() method on a null, it means that Auth::user()->business is returning null which means that the authenticated user does not have a business relationship.

Also, if you are using Laravel 5.5, you can use the optional() method which will act as a null object pattern:

{{ optional(Auth::user()->business)->getCompanyName() }}

You can read more about the optional() method here: https://laravel.com/docs/5.5/helpers#method-optional

kfirba left a reply on Getting Error When Run A Command • 1 week ago

@Lalit In your createInvoice() method you have this line of code:

$data['details'] = '';

Which means you initialize the details key within the $data array to an empty string. Then somewhere else in that method, you call:

$data['details'][] = $details;

And you get your error. The reason for the error is that what you are calling the shorthand array_push() on a string. Usually in PHP you can do:

// initialize an array
$array = [];
// push items to the array
$array[] = 'Item A';
$array[] = 'Item B';
// Now the array looks something like:
// -> ["Item A", "Item B"]

// The above code is a shorthand for:
$array = [];
array_push($array, 'Item A');
array_push($array, 'Item B');
// -> ["Item A", "Item B"]

What happens in your code that you try to use the $data['details'] value as if it was an array when it is actually a string (remember the $data['details'] = ''; line of code).

What you need to do is change this line of code:

$data['details'] = '';

To:

$data['details'] = [];

Also, it is better if you try to debug your code by yourself. You will learn a lot. Try going through the stack trace whenever you have an error. I know it looks long and intimidating but once you get used to it, it is a breeze to do so :) Also, don't forget the Google is any developer's best friend!

kfirba left a reply on Getting Error When Run A Command • 1 week ago

@Lalit No, that's too much information. I just need to know what is the code at line 275 and in which functions it exists within

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 1 week ago

@eDesignary Well, I'm not sure why it's happening.

Can you try running the query manually from PHP using the raw PDO object?

You can get the PDO object like so:

DB::connection()->getPdo();

If you don't remember how to interact with PDO directly, check out the docs for PDO's statements

kfirba left a reply on Getting Error When Run A Command • 1 week ago

@Lalit I'd suggest you learn how to read those stack traces for your own benefit.

Anyway, it seems like your issue is with some code in your Invoice model class at line 275. What does line 275 looks like? Paste the full method code which line 275 resides in.

kfirba left a reply on Getting Error When Run A Command • 1 week ago

@Lalit try running the command in verbose mode:

php artisan invoices:generate -vvv

kfirba left a reply on Getting Error When Run A Command • 1 week ago

@Lalit Show me the full stacktrace of the error. I need to see on which line this error occurs

9th October, 2017

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 1 week ago

@splendidkeen There is no business method on the Auth facade. Are you actually trying to do something like:

Auth::user()->business->getCompanyName();

kfirba left a reply on Getting Error When Run A Command • 1 week ago

@Lalit

Look at your failed method. You are trying to pass the $exception object to the debug() method when it only accepts an array.

Change this line:

Log::debug('[Generate Invoice] Failure - ',$exception);

to:

Log::debug('[Generate Invoice] Failure - ', [$exception]);

Or just pass the $exception message:

Log::debug('[Generate Invoice] Failure - ', ['error' => $exception->getMessage()]);

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 1 week ago

@eDesignary When you view your database using the console or some other program, does the data seem to be valid? Does it show the proper date as you expect?

Also, try running the query manually against your database using the console or some other program and see what the returned data looks like.

I'm trying to see where exactly the data corruption is happening.

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 1 week ago

@eDesignary That's weird...

Does the data for the receipt_date seem to be valid on your database side?

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 1 week ago

@splendidkeen Hey

You called your variable company_name and not business:

->with('company_name', $business);

You should use it as follows:

{{ $company_name->getCompanyName() }}

Or just change the way you refer to your variable:

return view('partner.profile.index')->with('business', $business);

// or yet better (in my opinion):
return view('partner.profile.index', compact('business'));

kfirba left a reply on Split URL Like /intranet/Useful Resources/Test Folder/test 3/ • 1 week ago

@northplanet You can explode the string, remove the last item and implode it again:

$segments = explode('/', trim($url, '/'));
array_pop($segments);

return '/' . implode('/', $segments) . '/';

kfirba left a reply on Getting Error When Run A Command • 1 week ago

@Lalit I can't see it. Try pasting it again

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 1 week ago

@eDesignary What is the scheme for the receipt_date?

kfirba left a reply on Getting Error When Run A Command • 1 week ago

@Lalit I can't help you any further unless I see some code

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 1 week ago

@eDesignary Seems like it. It looks corrupted. What does this field should look like?

Anyway, try to exclude the receipt_date from the response and see if you get that error

kfirba left a reply on Getting Error When Run A Command • 1 week ago

@Lalit I'm gonna need to see your code to help with that. Please share your job class here. Paste the code between triple backticks so it gets formatted nicely:

``` // code here ```

kfirba left a reply on Is It Possible To Get Title And Thumbnail Image From Youtube Video Using Laravel ? • 1 week ago

@wardaddy Sure. It shouldn't be complicated at all. Let me know if you need help.

kfirba left a reply on Malformed UTF-8 Characters, Possibly Incorrectly Encoded • 1 week ago

@eDesignary I believe the source of this error message is when Laravel tries to convert the $receipts to JSON. What does the $receipts variable looks like? Can you try and post a dd() here?

Please ensure that your database driver is using some kind of utf8 encoding.

kfirba left a reply on Is It Possible To Get Title And Thumbnail Image From Youtube Video Using Laravel ? • 1 week ago

@wardaddy You can just use (Youtube Data API)[https://developers.google.com/youtube/v3/docs/videos].

It seems like someone has created a wrapper for Laravel: https://github.com/alaouy/Youtube

Good luck!

kfirba left a reply on Why I Can't Get All Details According To User From Database? • 1 week ago

@hemal You have user_id column on your profiles table right?

It seems you got your relationships mixed a bit. It should be:

User -> HasOne -> Profile
Profile -> BelongsTo -> User
// User.php

public function profile()
{
    return $this->hasOne(Profile::class); // assumes there is a `user_id` column in the `profiles` table
}

// Profile.php

public function user()
{
    return $this->belongsTo(User.php);
}

kfirba left a reply on Getting Error When Run A Command • 1 week ago

@Lalit Hey.

My guess is that you forgot to import the Exception class at the top of the GenerateInvoice class which means that every reference to the Exception class in that file will actually result in an attempt to use the App\Jobs\Exception.

The fix should be rather easy, simply add this to the use statements in your job file:

Use Exception;

kfirba left a reply on Why I Can't Get All Details According To User From Database? • 1 week ago

@hemal Hey.

You need to tell Eloquent that you also want to load the relationship profile for the authenticated user. You can do it by calling the load method or just try to access the profile property off of the user object:

Auth::user()->load('profile'); // Now the user has a `profile` attribute
Auth::user()->profile; // will detect that `profile` is a relationship and will fetch it for you.

Please read more about relationships in Eloquent here: https://laravel.com/docs/5.5/eloquent-relationships

I would also suggest to carefully read this: https://laravel.com/docs/5.5/eloquent-relationships#eager-loading

kfirba left a reply on Prevent Laravel_session Before Authentication • 1 week ago

@Kolorbon You can certainly be less harsh. I believe @Snapey was just trying to point you to the default middlewares that are attached to every route in the web group (a.k.a the routes/web.php file)

Anyways, I think you can do that by overriding the StartSession middleware.

If you take a look at the App\Http\Kernel class there is a $middlewareGroups variable that has middlewares configured for the web and api groups. One of the web middlewares is the \Illuminate\Session\Middleware\StartSession class I mentioned before.

This middleware is responsible for generating Laravel's session and sending it with the response. What you can do is create your own session middleware which will extend that middleware and override the handle method to only add the cookie to the response in case the user is authenticated.

It may look something like:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\Middleware\StartSession;

class CustomStartSession extends StartSession
{
    public function handle($request, Closure $next)
    {
        // The `terminate` method of StartSession checks on that value.
        $this->sessionHandled = true;

        // Delegates to the parent's `handle` method if we should enable sessions for the current reuqest.
        if ($this->shouldEnableSession()) {
            parent::handle($request, $next);
        }
    }

    protected function shouldEnableSession()
    {
        return auth()->check();
    }
}

Make sure you replace the original StartSession middleware with our CustomStartSession middleware in the Kernel class.

13th September, 2017

kfirba left a reply on Find The Number Of Change Rows • 1 month ago

@young_artisan Hey

It may not answer your question but you may be interested in my answer for another thread where I suggest a better way to import bulks of data while inserting new rows and updating old ones: https://laracasts.com/discuss/channels/eloquent/performant-way-to-mass-update-or-create/replies/365924

As for your question, the easiest way to calculate that is to run a simple select count on your database prior to inserting/updating:

$newRows = count($values) - Model::whereIn('your_primary_key', $values)->count();

kfirba left a reply on Performant Way To Mass "update Or Create" • 1 month ago

@pilat ORM is great but sometimes it's not the most performant solution.

Don't be afraid to "stray off" the ORM way. I LOVE ORM but many times I find myself writing custom queries in order to squeeze more performance from my application.

As for the max query length, you can just run: show variables like 'max_allowed_packet' to see what the max query length is set on your server. Of course, you can change this setting. To increase the max_allowed_packet, open the my.ini/my.cnf under [mysqld] section and alter the setting. Once the change is done you would have to restart the server.

kfirba left a reply on Performant Way To Mass "update Or Create" • 1 month ago

@pilat Hey.

TL;DR I've written a class that utilizes MySQL's on duplicate key update feature (see code below).

I've actually had a case where I needed to load massive Excel files into my database (The excel file was exported from another CRM program). The thing is that the customer required that if a record that already exists in my database also appears in the Excel file, he wants to update my local database with the new data from the Excel file.

So I've gone ahead and implemented that very naively: loop through the Excel rows and for each row if it exists update it, otherwise create it.

Well, it worked but it was really slow when the Excel file had like 2k rows or even more (Don't forget the constraints that the database has to check every time we insert or update a record).

So I started thinking what can I do in order to improve that? I ended up using MySQL's on duplicate key update feature.

So to get you familiar with this feature, just as the name suggests, it attempts to insert the rows into the database. When it encounters a duplicate UNIQUE constraint or duplicate PRIMARY KEY, it will automatically run an update statement for that row. Sounds good right? However, you might wonder: "Oh well, MySQL still internally does all that checking behind the scenes, why would it be significantly faster"?

There is a short answer for that. Usually, the time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:

  • Connecting: 3
  • Sending query to server: 2
  • Parsing query: 2
  • Inserting row: 1 × size of row
  • Inserting indexes: 1 × number of indexes
  • Closing: 1

(The information above was taken from MySQL's website)

So basically, there is a cost we can't do anything about which is connecting, sending the query, parsing it and terminating the connection. This cost is as high 8. it takes 80% of the time (Given we are inserting 1 row with 1 index only)!

So the code is pretty straightforward:

namespace App\Support;

use Illuminate\Support\Facades\DB;

class ResourceImporter
{
    /**
     * Inserts or updates the given resource.
     *
     * @param       $table
     * @param       $rows
     * @param array $exclude The attributes to exclude in case of update.
     */
    public function insertOrUpdate($table, $rows, array $exclude = [])
    {
        // We assume all rows have the same keys so we arbitrarily pick one of them.
        $columns = array_keys($rows[0]);

        $columnsString = implode('`,`', $columns);
        $values = $this->buildSQLValuesFrom($rows);
        $updates = $this->buildSQLUpdatesFrom($columns, $exclude);
        $params = array_flatten($rows);

        $query = "insert into {$table} (`{$columnsString}`) values {$values} on duplicate key update {$updates}";

        DB::statement($query, $params);

        return $query;
    }

    /**
     * Build proper SQL string for the values.
     *
     * @param array $rows
     * @return string
     */
    protected function buildSQLValuesFrom(array $rows)
    {
        $values = collect($rows)->reduce(function ($valuesString, $row) {
            return $valuesString .= '(' . rtrim(str_repeat("?,", count($row)), ',') . '),';
        }, '');

        return rtrim($values, ',');
    }

    /**
     * Build proper SQL string for the on duplicate update scenario.
     *
     * @param       $columns
     * @param array $exclude
     * @return string
     */
    protected function buildSQLUpdatesFrom($columns, array $exclude)
    {
        $updateString = collect($columns)->reject(function ($column) use ($exclude) {
            return in_array($column, $exclude);
        })->reduce(function ($updates, $column) {
            return $updates .= "`{$column}`=VALUES(`{$column}`),";
        }, '');

        return trim($updateString, ',');
    }
}

The usage is as follows:

$resourceImporter->insertOrUpdate(
                'users', // table name
        $rows, // array represenation of the rows to insert (assoc array where the key is the same as the DB column name)
                $excludeFromUpdate // Fields you want to exclude (excluded from the $rows parameter above) when a row is being updated. For example, if each row has a default `created_at` set to now, you may want to exclude the `created_at` update field when you update a row since it was created somewhen else in the past.
            );

Note that the class returns the generated query right after it executes it.

As you can see, this class isn't limited to a specific resource type. You can import users, products, articles or anything else you want with it.

Hope it helps.

11th September, 2017

kfirba left a reply on Why Does Factory Double The Count Of Records I Entered And Expect? • 1 month ago

@ejobity Glad it helped you :).

10th September, 2017

kfirba left a reply on Why Does Factory Double The Count Of Records I Entered And Expect? • 1 month ago

@ejobity Hey.

I'm pretty sure that your model factory for EmployerAddress requires an employer_id column so you have something like that in your model factory:

$factory->state(App\EmployerAddress::class, function (Faker\Generator $faker) {
    return [
        'employer_id' => factory(Employer::class)->create()->id
    ];
});

When you have it this way, every time you try to create an EmployerAddress it's going to create an Employer along with it.

What you need to do is to change the definition of your model factory to accept a callback and then pass an employer_id manually so the callback won't trigger:

$factory->state(App\EmployerAddress::class, function (Faker\Generator $faker) {
    return [
        'employer_id' => function () {
            return factory(Employer::class)->create()->id;
        }
    ];
});

Now if you pass an employer_id the callback won't run and you won't get additional Employer:

factory(Employer::class, 3)->create()->each(function (Employer $employer) {
    factory(EmployerAddress::class, ['employer_id' => $employer->id])->create();
});

9th September, 2017

kfirba left a reply on Are PHP Sessions Trustworthy? • 1 month ago

@thebigk SSD is indeed faster than HDD but I'm pretty sure that sessions creation and read aren't sequential so it also takes MUCH longer to read and write to the session compared to a memory (RAM) based solution such Redis.

Why do you think Redis is scary :/? Redis is awesome :)

Maybe familiarize yourself with Redis through Jeffrey's awesome Redis series: https://laracasts.com/series/learn-laravel-and-redis-through-examples

kfirba left a reply on Are PHP Sessions Trustworthy? • 1 month ago

Just as you suggest, I think the issue is with your session driver. File session storage is limited the the disk I/O capability and it's prone to race conditions.

Have you tried using something like redis for the session storage? I would give it a try and see if it solves the problem

7th September, 2017

kfirba left a reply on Set A Boolean On My Model Of Is_queued • 1 month ago

@chrisblackwell well without knowing more context I can't offer much.

I would try to play with the job's __wakeup and ‘__sleep` methods as they will trigger before the job is queued and when the job is resolved from the queue. Just make sure you view the original implementation for those methods so you don't break the job.

6th September, 2017

kfirba left a reply on Restore Soft Deleted Record With Alert Using Title From Record • 1 month ago

@zettz Fetch the record before restoring it and grab some data off of it. You can also use the high order tap here:

$post = tap(Post::onlyTrashed()->find($id))->restore();
Alert::success("Post '{$post->title}' has been restoed.")->persistent('Close');

return redirect()->route('posts.index');

kfirba left a reply on Set A Boolean On My Model Of Is_queued • 1 month ago

@chrisblackwell Is there a reason you don't want to manually mark that flag when you queue the job and when the job is finished? For example:

public function store()
{
    Model::create([
        /* ... */
        'is_queued' => true;
    ]);

    MyJob::dispatch($model);
}
class MyJob implements ShouldQueue
{
    protected $model;

    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    public function handle()
    {
        // Perform the logic needed here
        
        $this->model->update(['is_queued' => false]);
    }
}

kfirba left a reply on How To Apply Same Query To Multiple Eloquent • 1 month ago

@vinodjoshi Hey

Are you talking about a query scope? If that so, simply create a trait and use it in your models.

trait YourTraitName
{
    public function scopeSomeScope($query, $parameter)
    {
        return $query->where(...);
    }
}

Now in your models:

class Customer extends Model
{
    use YourTraitName;
}

And use the scope wherever necessary:

Customer::someScope($argumentIfNeeded)->get();

kfirba left a reply on What Frameworks Did Laracasts Use To Develop Its Website? • 1 month ago

Laravel all the way :)

2nd September, 2017

kfirba left a reply on Laravel Cache Page For 1 Second. • 1 month ago

@updatesvc Hey.

What you're describing here is pretty standard use-case. What is it that you're struggling with?

A naive approach would be, in your controller:

cache()->remember('items-cache-key', 0.17, function () {
    return Items::all();
});

The remember() method will try to pull the item from the cache if it's in there and return it. Otherwise, it will execute the callback and cache the callback response. I'm using a 0.17 as the method accepts the number of minutes so 1 / 60 is roughly 0.17.

24th August, 2017

kfirba left a reply on How To Stop<script> Tag To Enter In The Db • 1 month ago

@devlanga Hey.

You can just escape the string:

htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false);

Actually, laravel registers a global method to help you with that:

e($value);

16th August, 2017

kfirba left a reply on Create Class Object From String • 2 months ago

@DoppyWoppy Well, that won't work since your class is not auto-loaded by composer since it's not following PSR-4.

Make sure you either require the class in or you add it to your composer auto-load files array.

15th August, 2017

kfirba left a reply on Create Class Object From String • 2 months ago

@DoppyWoppy How does the definition of the classtest_class looks like?

13th August, 2017

kfirba left a reply on How To Regex Everything In Div • 2 months ago

@phantanvietpk perhaps something like:

<div class="ui-box pnl-packaging-main">[\r\n]*([\S\s]*)[\r\n]*<\/div>

This will match anything inside the <div> tag and will allow line breaks

12th August, 2017

kfirba left a reply on Reject() • 2 months ago

@Asmaa_Mohamed Just as @topvillas said. You can read more about this method here: https://laravel.com/docs/5.4/collections#method-reject

Also, I'd suggest you familiarize yourself with the collection's methods: https://laravel.com/docs/5.4/collections#available-methods

kfirba left a reply on Redirect "legacy" .html And .php Extensions In Nginx • 2 months ago

@mikefolsom You can just go with a simple, scalable laravel based solution and use the router for that:

// web.php
Route::get('our-locations.php`, '[email protected]`);
// RedirectsController.php

public function locations()
{
   return redirect('locations', 301);
}

It sucks that we need to use an intermediate controller in order to achieve a simple redirect. Luckily, Laravel 5.5 has an easy way to do that:

// Laravel 5.5+ only:
Route::redirect('our-locations.php', 'locations', 301);

kfirba left a reply on Blade Destroys Json Object Passed To Vue.js When It Contains Whitespaces • 2 months ago

@SwissNight This is how vue works. You need the double-quotes since you can also pass an expression as an argument. For example:

<example :some-key="3+4"></example>

In the above case, the value of someKey will be 7 and not the string 3+4.

kfirba left a reply on Pass Associative Array From Blade To Vuejs • 2 months ago

@yburan Hey.

How exactly are you passing that array to vuejs? Ensure that you are binding the property so vue knows to interpolate that as JSON:

<vue-component :assoc-array="{{ $lorem }}"></vue-component>

kfirba left a reply on Inject Current User Id Automatically When Post Is Created • 2 months ago

@ronon Hey.

You can do that by using eloqent's lifecycle events.

You can start with your boot method:

// Post.php

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

    static::creating(function ($post) {
        return $post->user_id = auth()->id();
    });
}
Edit Your Profile
Update

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