Question

Title looks odd. Let me explain it.

I have proper Model structure for Post. Post has a body column. But I need to use it in view two diffrent style.

One of them markdown parsed style. I use MarkdownNext package. If i call $post->body->markdown() it will handle Markdown::render($post->body). At the same time $post->body will return plain text.

Was it helpful?

Solution

You cannot do this directly in Laravel, but you can use PHP to reproduce it.

This is untested code, but should work. Basically you create an accessor that returns an object of a class Markdown, you just need to inject the body into that object:

class Post extends Eloquent {

    public function getBodyAttribute($originalValue)
    {
        return new Markdown($originalValue);
    }

}

The class will receive the body and store it into a property. The magic method __toString will be used every time your code tries to use $this->body as string, and, if you do $this->body->markdown(), well this is an object that has this method and it will just render the body using the MarkdownNext class.

class Markdown {

    public $body;

    public function __construct($body)
    {
        $this->body = $body;
    }

    public function __toString()
    {
        return $this->body;
    }

    public function markdown()
    {
        return MarkdownNext::render($this->body);
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top