php laravel call function from collation \App\CourseStart->find(any)->students->count() with concatenate

Viewed 43

in first i can write this \App\CourseStart->find(any)->students->count() and will work fine put I am forced to concatenate the variables same $object->$k->count()

    $object = (`\App\CourseStart->find(any)) collation laravel

    App\CourseStart {#1309 ▼
    #dates: array:2 [▶]
    #fillable: array:15 [▶]
    #connection: "mysql"
    #table: "course_starts"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:6 [▶]
    #original: array:6 [▶]
    #changes: []
    #casts: []
    #classCastCache: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: array:1 [▶]
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #guarded: array:1 [▶]
    #forceDeleting: false
    }

    $k = 'students'  is relation

    so $object->{$k}     =  \App\CourseStart->find(any)->students this work 100%

    Illuminate\Database\Eloquent\Collection {#1310 ▼
      #items: array:2 [▼
      0 => App\Student {#1311 ▶}
      1 => App\Student {#1314 ▶}
    ]
    }

$object->{$k}->count(); work get resulte "2"

$f = ['count()','','']

now i try write this $object->{$k}->$f[0] and $object->$k->{$f[0]}

i have this msg error

Exception
Property [count] does not exist on this collection instance.

now how concatenate function count() to $object->{$k}

Not sure which address is appropriate for the question?

1 Answers

after some experiments

$f = ['count','','']// remove brackets of the functions
$f2 = $f[0];// assign to a variable for extracting the function from the array
$object->{$k}->$f2()// this will work

source: https://www.php.net/manual/en/functions.variable-functions.php

I tested it in a project of mine as beloved:

$x = Page::where ( 'slug', $page_slug );
        $fA = ['count','get',''];
        $f = $fA[0];
        dd( $x->$f());
Related