Member Since 4 Years Ago

Experience Points 247,785
Experience Level 50

2,215 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 1541
Best Reply Awards 114
Best Reply
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.


    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.


    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

23 May
3 months ago

kfirba left a reply on Pass Associative Array From Blade To Vuejs

@wallyj Hey!

What exactly are you trying to do? I will need to see some code in order to understand what's not working for you. Basically, if you can see the property in Vue DevTools, you should be able to easily iterate over it with v-for:

            <tr v-for="item in items">
                <td v-text="item.title"></td>
                <td v-text="item.subtitle"></td>

    export default {
        props: {
            items: {
                type: Array,
                default: [],
30 Mar
5 months ago

kfirba left a reply on How To Mock HasMany() Resonse

Hey @tylerssn

Generally, I'm against mocking Eloquent, but this is another discussion.

For your specific case, your code attempts to find a Documentation object by a label and return the first result (which is returning a DocumentationMock as you declared in your test). Then you call the versions() method on the DocumentationMock object but you specified the expectation on the DoumentationFacade.

What you should do is to mock the DocumentationMock and set an expectation on that object:

$documentationMock = Mockey::mock(Documentation::class, function ($mock) use ($documentationVersions) {

Your test should look something like this:

public function testGetDefaultVersion()
         * Mock Config::get('docs') and assert that it will be called in this test at some point
        $repoId = 'main';

        $documentationVersions = new Collection([
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'development']),
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'main']),
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'yas yas yas']),

         * @var Documentation $documentationMock
        $documentationMock = Mockey::mock(\App\Documentation::class, function ($mock) use ($documentationVersions) {

        DocumentationFacade::shouldReceive('where')->with('label', $repoId)->once()
            ->andReturn(new Collection([$documentationMock]));

        $actualDefaultVersion = $documentationMock::getDefaultVersion('main');

21 Dec
8 months ago

kfirba left a reply on Request Failed With Status Code 401

@jet Hey.

It simply means that you're unauthorized to perform this action. Ensure that the API key that you're using is correct.

Try to console.log the URL:


Also, I would put it in a single line to prevent new lines from leaking to the URL:

20 Nov
9 months ago

kfirba left a reply on Performant Way To Mass "update Or Create"

@hansz Well, you can't, at least not in one query.

You will need some code to split your Excel file into separate models (tables) and run them one after another, probably in a logical way where you'd get ids for foreign keys.

Do you have a specific excel file you want to import?

28 Feb
1 year ago

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

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

21 Feb
1 year ago

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

@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 the now() 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, it will simply build the model and won’t invoke the models **now()**method. Maybe what we can do is to build the model and check to see if a now() method exists on that model. If so, we also invoke that method. But again, what happens if there is a now() 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


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!

19 Jan
1 year ago

kfirba left a reply on AuthenticateSession Middleware

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

12 Jan
1 year ago

kfirba left a reply on Performant Way To Mass "update Or Create"

@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

08 Jan
1 year ago

kfirba left a reply on What Is $.extend In Spark Js

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

27 Dec
1 year ago

kfirba left a reply on MySQL/Eloquent: Grouping By Date In Users Timezone

@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 “created_at” 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 “UTC” 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 “whereBetween” method to fetch those records.

Let me know if you need code samples :)!

24 Dec
1 year ago

kfirba left a reply on Order By The Latest (most Recent) Related Model

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

23 Dec
1 year ago

kfirba left a reply on Job Number - Auto Assign Through Create Form

@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

@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

22 Dec
1 year ago

kfirba left a reply on Delete Without Using Forms Collective

Just write the HTML yourself:

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

    {{ csrf_field() }}

    <button type="submit" class="btn btn-danger">Delete</button>
21 Dec
1 year ago

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

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

20 Dec
1 year ago

kfirba left a reply on AuthenticateSession Middleware

@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

13 Nov
1 year ago

kfirba left a reply on Processing Chunked Uploads Help Please

@NotAGoodCoder hey!

I think that instead of “reinventing the wheel” you can use a native OS api such as the cat command. The cat 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 Symfony’s Process class to execute the command above.

Good luck!

04 Nov
1 year ago

kfirba left a reply on User Specified Download Link

@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

@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

@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

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


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
    abort_unless(optional(auth()->user())->canDownload($hash), 404);
    return response()->file($pathToFile);
03 Nov
1 year ago

kfirba left a reply on Encrypt Frontend Api Post Data & Decrypt Laravel Backend

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

28 Oct
1 year ago

kfirba left a reply on Contact Form Validation Error

@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 Run A Custom Artisan Command In Browser And Display Progress With Progress Bar

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

27 Oct
1 year ago

kfirba left a reply on How To Retrieve Data In Array Object?

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

kfirba left a reply on How To Retrieve Data In Array Object?

@hemal Change your query:

public function index($slug)
    return Post::where('slug', $slug)->get();
26 Oct
1 year ago

kfirba left a reply on Which User Deleted What?

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

21 Oct
1 year ago

kfirba left a reply on Eloquent Vs Query Builder, Why?

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

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

            "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?

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

20 Oct
1 year ago

kfirba left a reply on Order By Short To Long

@minions Hey.

You can just add an orderByRaw clause:

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

Alternatively, you can just sort the results:

$db = Book::where('title', 'like', '%' . implode('%', $keyword) . '%')
$title_book = $db->pluck('title')->sortBy(function ($title) {
    return mb_strlen($title);
10 Oct
1 year ago

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System

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


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


kfirba left a reply on Undefined Method/Variable Problems On My 2nd System

@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

@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

@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 try to interact with it as if it was an array:

$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'] = '';


$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

@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

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


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

@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

@Lalit try running the command in verbose mode:

php artisan invoices:generate -vvv

kfirba left a reply on Getting Error When Run A Command

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

09 Oct
1 year ago

kfirba left a reply on Undefined Method/Variable Problems On My 2nd System

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


kfirba left a reply on Getting Error When Run A Command


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


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

@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

@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

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

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

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

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

On second thought, I think dirname() can do what you are looking for:

dirname('/intranet/Useful Resources/Test Folder/test 3/');
// -> "/intranet/Useful Resources/Test Folder"