Search code examples
phplaravelhelper

How to call faker class via helper function as property rather then array


I am trying to create a helper function for the faker package to be able to easily create fake data.

Currently I have a function which works as an array function. eg. faker('sentence')

But I want it to work by calling properties in the same way it is used in the laravel factory classes, but cant seem to get it to work.

eg. faker()->sentence

Currently I have

use Faker\Factory;

if (!function_exists('faker')) {
    /**
     * Get faker data
     *
     * @return Faker\Factory;;
     */

    function faker($property)
    {
        $faker = Factory::create();
        return $property ? $faker->{$property} : $faker;
    }


}

Solution

  • Actually it Looks like the issue I had was to do with the way the helper was being loaded. The faker function already can be called both ways.

    faker('name')

    faker()->name

    use Faker\Factory;
    
    if (!function_exists('faker')) {
        /**
         * Get faker data
         *
         * @return Faker\Factory;;
         */
    
        function faker($property)
        {
            $faker = Factory::create();
            return $property ? $faker->{$property} : $faker;
        }
    
    
    }