2

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

}

2 Answers 2

1

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;?>";
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I agree their should be some php code it was their i had taken it out while just trying fixes and not put it back. but still it had no value passed.
Did you debug directive's code? What if you return a value like echo "Something" instead of $i? Does this work?
0

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.

2 Comments

Thanks I agree their should be some php code it was their i had taken it out while just trying fixes and not put it back. but still it had no value passed. as it works without the return "<?php echo $i;?>";
@ItsLewis Did you run this command which will delete the cached views. php artisan view:clear, it may be the one of the reason, because views are already cached and it is not taking this new directive ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.