user2002495
user2002495

Reputation: 2146

Laravel 4 Blade: How to use custom models?

Normally in Laravel I call a model by creating something like this:

class Config extends Eloquent {

protected function getBaseUri() {
    return sprintf(
        "%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['HTTP_HOST'], '/project/public/assets/'
    );
}

public static function getBaseImagePath() {
    return $this->getBaseUri() . 'image/';
}

}

and call it somewhere in php files like this:

echo Config::getBaseImagePath();

Now, I'm migrating into .blade.php and I need to call the same function from the model, so I did this somewhere in the blade:

{{ Config::getBaseImagePath() }}

And it's not working (weird enough, since what I know is all blade doing is convert {{ }} tags to php tags). Can anyone explain how to make this work? Thanks.

Error I'm getting is:

Call to undefined method Illuminate\Config\Repository::getBaseImagePath()

Upvotes: 1

Views: 1135

Answers (2)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

You are using a Laravel class name Config.

I don't know why it works in PHP and not in Blade, but it shouldn't.

So you have some options:

1) Change the Config Laravel alias in app/config/app.php

2) Change your Config class name.

3) Create a namespace for your classes:

<? namespace MyName\Services

class Config extends Eloquent {

    protected function getBaseUri() {
        return sprintf(
            "%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['HTTP_HOST'], '/project/public/assets/'
        );
    }

    public static function getBaseImagePath() {
        return $this->getBaseUri() . 'image/';
    }

}

Execute

composer dump-autoload

And use it

{{ \MyName\Services\Config::getBaseImagePath() }}

Upvotes: 4

The Alpha
The Alpha

Reputation: 146191

In your code

{{ Config::getBaseImagePath() }}

It's pointing to the laravel's Illuminate\Config\Repository class where this method is not available. Change the name or use namespace. Also, you can't use $this in a static method, instead you can use

public static function getBaseImagePath() {
    return static::getBaseUri() . 'image/';
}

Upvotes: 2

Related Questions