Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel access blade variable in helper

I have a public variable $publisher shared to all view:

$view->with('publisher', $publisher);

Example: I would like to check this publisher is named as 'main' and is status 'active', hence I have to write if statement in blade like this:

@if ($publisher->name == 'main' && $publisher->status == 'active')
    // Code here
@endif

It's replicated for all the blade file, therefore I created a custom helper file at app/Helpers/general.php, named it as isMainPublisher($publisher):

function isMainPublisher($publisher) 
{
    return ($publisher->name == 'main' && $publisher->status == 'active') ? true: false;
}

The blade if statement will be changed to:

@if (isMainPublisher($publisher))
    // Code here
@endif

I am thinking to shorten the blade code to this:

@if (isMainPublisher())
    // Code here
@endif

But app/Helpers/general.php will not access the blade variable $publisher, is there anyway or actually no way to access blade variable in helper? Thanks.

like image 784
Momo Avatar asked Nov 24 '25 06:11

Momo


1 Answers

Essentially, short of setting the publisher name on an internal variable of the helper class, isMainPublisher($publisher) is your best choice, AND its way more idiomatic than the other option.

In order to get isMainPublisher() to work (possibly), you would have to work with a hacky global declaration, which even then, would probably not work as it is not available to the class

ALTERNATIVELY, you could add the helper onto the model as a method:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Publisher extends Model
{
    // Your new helper method
    public function isMain()
    {
        // some logic to determine if the publisher is main
        return ($this->name == "main" || $this->name == "blah"); 
    }
}

...and then call it like this:

$publisher->isMain();

Which in my point of view, is the superior choice as it reads like you'd say it.

I hope this helps!

like image 53
Derek Pollard Avatar answered Nov 27 '25 21:11

Derek Pollard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!