kfirba

Hire Me

Experience

219,895

113 Best Reply Awards

  • Member Since 3 Years Ago
  • 1290 Lessons Completed
  • 20 Favorites

28th February, 2018

kfirba left a reply on Are There Any E-commerce Package To Create E-commerce Site Easily? • 3 months ago

@anandmainali5 Hey. Have you tried googling "ecommerce laravel"? The first result seems pretty good and it's also free: https://aimeos.org/

21st February, 2018

kfirba left a reply on [Package] Factor - Expressive Way To Use Laravel's Factories • 3 months ago

@bobbybouwmann glad you like it! There are still a few edge cases I’m currently trying to decide with myself how to solve. For example, what if your actual model has a method called `states or `now? Right now, Factor won’t delegate to the model instance when these two methods are invoked since they are defined on the proxy object.

One way I thought about tackling it is to use some logical guard on the ‘states())` and thnow()` methods to check to see if a model has already been generated. If it has, we delegate to the model instance if it has those methods defined. If they do not exist, use the proxy object’s methods.

However, that begs the question, what if the user has a now() method on his model and he simply wants to invoke it. By calling now() on the proxy object, given we haven’t built the model yet, will simply build the model and won’t invoke the model’s ’s method. Maybe what we can do is to build the model and check to see if a if amethod exists on that model. If so, we also invoke that method. But again, what happens if there is a is a method on the model but we do not want to invoke it?

What do you think?

kfirba started a new conversation [Package] Factor - Expressive Way To Use Laravel's Factories • 3 months ago

Hey!

I've just published a package that lets you use the built-in model factories more expressively, Factor. I've also written a blog post that goes a little bit more in details about this package: https://kfirba.me/blog/factor-short-and-expressive-way-to-use-laravels-factories

Would love to hear what you think about this!

19th January, 2018

kfirba left a reply on AuthenticateSession Middleware • 5 months ago

@mkarnicki Thanks for sharing :). I'm glad you found it helpful!

12th January, 2018

kfirba left a reply on Performant Way To Mass "update Or Create" • 5 months ago

@pilat I'm glad you liked it!

I've actually written a small library to generate the appropriate query along with its bindings: https://github.com/kfirba/import-query-generator

I've also published an in-depth blog about that feature that I think can come handy: https://kfirba.me/blog/performant-mass-update-or-create-strategy-for-data-imports

8th January, 2018

kfirba left a reply on What Is $.extend In Spark Js • 5 months ago

@makapaka I don't own Spark so I'm not sure what dependencies it has but I'm pretty sure this is jQuery's extend() method: https://api.jquery.com/jquery.extend/

Basically, it merges the two given objects. By passing true as the first argument, it will tell jQuery to recursively merge the two given objects.

Basic usage:

let obj1 = { a: 1, b: 2, c: 3 };
let obj2 = { d:4, b: 5 };

$.extend(true, obj1, obj2); -> // { a:1, b:5, c:3, d:4 }

To illustrate what happens when the first argument is true (from the docs):

let object1 = {
  apple: 0,
  banana: { weight: 52, price: 100 },
  cherry: 97
};

let object2 = {
  banana: { price: 200 },
  durian: 100
};
 
// Merge object2 into object1, recursively
$.extend( true, object1, object2 );

// -> {"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}

Note that the banana's price is 200 and not 100.

29th December, 2017

27th December, 2017

kfirba left a reply on MySQL/Eloquent: Grouping By Date In Users Timezone • 5 months ago

@robjbrain hey!

Making the timezone calculation in your query is indeed a way to go about that, however it might get slower and slower as your database grows. Think about it, mysql isn’t magical. For reach row in your database it will convert the date to the correct timezone and then compare it. This needs a little bit more research, but I’m not sure mysql will use the index on the he `create column in that situation as the index is only correct for UTC timezone.

I would like to suggest an alternative way to achieve that while ensuring mysql can use an index to perform the search.

If you know the user’s timezone, you can then calculate what is the right `U time that reflects their timezone. For example, if you want all data between “2017-11-05 00:00:00” and “2017-11-05 23:59:59” in the user’s timezone and you know their offset is +10hours, you can convert your UTC time t reflect that and look for any comments between “2017-11-04 14:00:00” and “2017-11-05 13:59:59”.

If you use Carbon this gets as easy as calling a timezone set method on the object.

After you get that done, you can use Eloquent’s `whereBetwe method to fetch those records.

Let me know if you need code samples :)!

24th December, 2017

kfirba left a reply on Order By The Latest (most Recent) Related Model • 5 months ago

@DoeJohn Hey.

In order to achieve that you'll need to join the posts table. Every time you need to sort the main "model" by its relationship, the relationship should be joined rather than lazy loaded (eagerly loaded).

23rd December, 2017

kfirba left a reply on Job Number - Auto Assign Through Create Form • 5 months ago

@zaster Hey.

There are many ways to achieve that. I don't think an auto-incremented number is what you actually want. Consider the following scenario:

  1. User A views the form to add a new job. The system offers job number 143 (last stored job is 142).
  2. User B at the same times views the form to add a new job. The system also offers job number 143 to him (last stored job is still 142).
  3. Now it's a race between User A and User B. The first one to complete the form will get job number 143 and the other one will get an error when he tries to create the job (the ID field is unique).

I would probably use something like UNIQUEID instead or, you can make a rule in your system that each User's ID should be the first digit(s) of your job number. For example, a user with an ID of 456 will always have his generated job's ID to start with 456 and then just an incrementing number: 4561, 4562, 4563, ... 4561780...

This will ensure a unique incrementing job ID for each user.

kfirba left a reply on How To Add Class="active" To The Current Selected Menu Item • 5 months ago

@pickab00 Hey!

I've actually written a short blog about handling that situation. You may want to give it a read: https://kfirba.me/blog/mavigator-marking-your-navigators-with-ease

22nd December, 2017

kfirba left a reply on Delete Without Using Forms Collective • 5 months ago

Just write the HTML yourself:

<form method="post" action="{{ route('articles.destroy', $articel) }}">
    {{ method_field('patch') }}

    {{ csrf_field() }}

    <button type="submit" class="btn btn-danger">Delete</button>
</form>

21st December, 2017

kfirba left a reply on Database / Model Design For One To Many, But Only 1 Active. • 5 months ago

@noleafclover614 Unless I don't fully understand what you need, it sounds like you need a contracts table with an organization_id to associate contracts with the correct organization. Also, you will need a column like active_contract_id in the organizations table to hold the current active contract.

The organization should be able to watch all their contracts easily, both old and new (the contracts table has an organization_id column) and pick one of them to be active (which will set the active_contract_id column value on the organizations table's record).

20th December, 2017

kfirba left a reply on AuthenticateSession Middleware • 5 months ago

@bastiaan89 I know it's an old thread but I thought that adding a more comprehensive resource about the AuthenticateSession middleware can be good for future reference: https://kfirba.me/blog/the-undocumented-authenticatesession-middleware-decoded

13th November, 2017

kfirba left a reply on Processing Chunked Uploads Help Please • 7 months ago

@NotAGoodCoder glad it helped you :).

kfirba left a reply on Processing Chunked Uploads Help Please • 7 months ago

@NotAGoodCoder hey!

I think that instead of “reinventing the wheel” you can use a native OS api such as the he command. The he command will read the files in small chunks and append them together. It will leave a very small memory footprint.

The command may look like:

cat file1 file2 file3 file4 > fullFilze

Just make sure you use the absolute file path so the command can find the files.

You can use Symfiny’s `Proce class to execute the command above.

Good luck!

4th November, 2017

kfirba left a reply on User Specified Download Link • 7 months ago

@sadiss There is a public folder in your application. Everything in that folder is basically user-accessible content. Say you have images/some-image.jpg file in the public folder, anyone could access that image by visiting: example.com/images/some-image.jpg.

As you noticed, the storage folder is not inside the public folder, hence no one should be able to access it directly. But sometimes we do want to make some content in that folder user-accessible. To do so, we create a symlink. What does that mean? A symlink is a nickname for any file that contains a reference to another file or directory. So say I create a symlink from public/some-symlink-name to storage/public when someone visits example.com/some-symlink-name, he will be presented with the contents of the storage/public directory. If we have a file in the path storage/public/my-image.jpg and symlink to that folder, the file will be accessible under example.com/some-symlink-name/my-image.jpg.

To create such symlink, you may do something like:

ln -s path/to/application/storage/public path/to/application/public/my-symlink-name

Laravel has a command: php artisan storage:link that creates a symlink automatically between your storage/public folder and the public/storage folders.

Well basically, if you don't know if you have a symlink, you probably don't have one. Otherwise, you can simply check that by going into your public directory and type: ls -la and see if the file type is l (symlink) instead of d (directory) or - (file).

kfirba left a reply on User Specified Download Link • 7 months ago

@sadiss As long as you don't symlink that folder to the public folder, then yea, no one can access that.

kfirba left a reply on User Specified Download Link • 7 months ago

@sadiss The storage folder is an internal storage. Unless you symlink it to somewhere in your public directory, no one can access that folder directly. There is a public directory in the storage folder that you can symlink but if your files are directly under the storage path, no one should be able to access them directly.

kfirba left a reply on User Specified Download Link • 7 months ago

@sadiss Hey.

You can make the request go through your app and determine whether the request is valid or not. What I would do is expose an endpoint to download files, maybe something like:

example.com/downloads/{hash}

Now you are going to associate any file in your database with some kind of a hash. You would then create a controller to respond to that URI and determine whether the user should have access to the file or not:

public function show($hash)
{
    // Perform the authorization here
    abort_unless(optional(auth()->user())->canDownload($hash), 404);
    
    return response()->file($pathToFile);
}

3rd November, 2017

kfirba left a reply on Encrypt Frontend Api Post Data & Decrypt Laravel Backend • 7 months ago

@makapaka Hey.

Symmetric encryption (what Laravel offers out of the box) uses a single key to encrypt and decrypt the data. In order to encrypt something on the frontend and be able to decrypt it at the backend, both the frontend and the backend need to share the same key. Okay, that's not hard to do, however, when you have your key in your frontend, anyone with basic skills can look for that key through your source code which makes it really useless to encrypt any data using that key.

If you wanna go down that route, you will need to use asymmetric cryptography - Public-Private key encryption where your frontend encrypts your data with a public key and your backend use the private key to decrypt the data.

Simply generate a key pair on your machine/server and use PHP's openssl functions.

28th October, 2017

kfirba left a reply on Contact Form Validation Error • 7 months ago

@kavi Can you format your code so it is actually readable? Use a triple backtick (```) before and after the code block.

kfirba left a reply on Preventing An Event Being Queued Twice • 7 months ago

test

alert('works');

kfirba left a reply on Testing Uploaded File • 7 months ago

Test

alert('works');

kfirba left a reply on Run A Custom Artisan Command In Browser And Display Progress With Progress Bar • 7 months ago

@khizer1030 Hey.

The only way I can think of to do this is to have an endpoint which triggers the command you want and return a channel which you can listen on your frontend for progress. Your command then should broadcast an event to let the frontend know what is the current progress of the command.

Basically, it will take the shape of:

  1. Ping some backend link: /scrape
  2. The server responds with a channel ID: scrapingChannelId:10
  3. You listen to that channel on your frontend. You can use Laravel echo or just vanilla socket.io
  4. Your command will broadcast an event every X seconds or when on any other condition
  5. Your frontend listens to that event and updates some kind of progress bar.

Good luck!

27th October, 2017

kfirba left a reply on How To Retrieve Data In Array Object? • 7 months ago

@hemal I'm really confused as to what you are trying to achieve...

Maybe you mean something like:

public function index($slug)
{
    return Post::whereHas('user', function($query) use ($slug) {
        $query->where('slug', $slug);
    })->get();
}

kfirba left a reply on How To Retrieve Data In Array Object? • 7 months ago

@hemal Change your query:

public function index($slug)
{
    return Post::where('slug', $slug)->get();
}

26th October, 2017

kfirba left a reply on Which User Deleted What? • 7 months ago

@imposition Yea? You will need to be more specific in order for us to help you

21st October, 2017

kfirba left a reply on Eloquent Vs Query Builder, Why? • 7 months ago

@Boubou I'm not doing a regular insert, I'm doing an insert select query. Basically, it will take a table structure and insert it. You can read more about it here: https://dev.mysql.com/doc/refman/5.7/en/insert-select.html

kfirba left a reply on Eloquent Vs Query Builder, Why? • 7 months ago

@Boubou well, it's gonna be a bit vague, but, it depends.

I try to keep everything super simple. If it's some simple query, I will definitely do that in the controller itself. If I need to some a bit more complex query I might offload that to a method on the model itself and if it is a complex query, I might extract a query object to do that.

For example, I have built some kind of an online shopping site for a customer, and for that very specific project, the user's cart had to be saved between sessions and never be deleted unless the user specifically emptied the cart or made an order. In order to achieve that, the cart is stored in the database for the user. Because the cart is stored in the database, its structure is very similar to what an order may look like. To me, it did not make sense to run a query for each cart item and "move" it to the orders table which is the easiest solution if you were using Eloquent to do that. Instead, I've written the following query:

DB::insert(
            "insert into order_product(order_id, product_id, quantity, price, created_at, updated_at)
            select '{$order->id}' as order_id, c.product_id, c.quantity, p.price, '{$order->created_at}' as created_at, '{$order->updated_at}' as updated_at
            from cart as c
            join price_list_product as p on p.product_id = c.product_id and p.price_list_id = '{$user->price_list_id}'
            where c.user_id={$user->id}"
        );

The query is not overly complicated but it felt a little bit disgusting keeping that query the controller so I simply extracted that query to a method on the model.

kfirba left a reply on Eloquent Vs Query Builder, Why? • 7 months ago

@Boubou Hey

Well, I find myself using both on the same project. I roll with Eloquent by default since it makes the code much more expressive than using the query builder. However, there are many cases where I find myself needing to write some custom query to achieve something (for example, using the on duplicate update feature of MySQL) that would result in many more queries if I stuck to Eloquent.

20th October, 2017

kfirba left a reply on Order By Short To Long • 7 months ago

@minions Hey.

You can just add an orderByRaw clause:

Book::where('title', 'like', '%' . implode('%', $keyword) . '%')
    ->take(10)
    ->orderByRaw('char_length(title) asc')
    ->get();

10th October, 2017

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

@splendidkeen Glad I could help :)

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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 • 8 months 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/ • 8 months 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 • 8 months ago

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

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

@eDesignary What is the scheme for the receipt_date?

Edit Your Profile
Update

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