ItsLewis
ItsLewis

Reputation: 73

Laravel - Array Output Issue

I'm trying to take an output from a db, search pass it over from a controller using compact, and then pass it to a custom blade helper.

When I pass over the db details I get a value of said users id and this can be displayed using

@foreach($SelectUser as $key => $UserArray)

     {{$UserArray->user_id}}

 @endforeach

I will get an output as expected of a users id e.g. 1.

When I try to combine this with my helper to change the value in to a readable username it dose not seam to output a value for the helper class to convert to a readable username.

    @foreach($selectUseras $key => $UserArray)

     @FindUsername($UserArray->user_id)

 @endforeach

helper class is

    public function boot()
{
 
    //A Helper to translate a user id number in to a readable username 

    Blade::directive('FindUsername', function ($id) {

        // Request infomation from the db useing eloquent
        $username = User::where('id', $id)
                    ->pluck('username');

        //Results to an array
        $arr = $username->toArray();

        //Filter through array results
        $i = implode(" ",$arr);

        return $i;
    
    });

}

Upvotes: 2

Views: 80

Answers (2)

Vikash
Vikash

Reputation: 3541

You need to print the values, not return. When blade file will be compiled and blade directive will be resolved, then it will only show the printed values like a php file does,

for ex: in a php file if you write $i = 1;, then it will not shown when it will be compiled in browser, it will only shows when you do echo $i;

So you need to return this

return "<?php echo $i;?>";

Don't forget to run php artisan view:clear, you need to clear your compiled view before updating the directive.

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

Blade directive should return not real value, but some php-code. You should change your directive to:

//Filter through array results
$i = implode(" ",$arr);

// return php-code which echo'es you value
return "<?php echo $i;?>";

Upvotes: 1

Related Questions