phplaraveleloquent

Laravel: How to use function of relation


I'm facing a situation where a I have to call a function from the controller of a relation instance. For better explanation I will write an example below

I have a Article controller in which I have a preview() function.

A User can have multiple Article.

Let's say that the preview() function parse a text and replace special pieces of text by the user's name.

So my function will looks like this

//In ArticleController
public function preview(Article $article , User $user){
    return str_replace("username", $user->name , $article->text);
}

But for a specific situation I want to display a preview of the article when I list all the users

So in UserController

public function index(){
    foreach( User::all() as $user){
        echo $user->articles[0]->preview( ... );
    }
}

Obviously this piece of code will not work.

But I'm more looking of the way to proceed when I face this kind demand.

Should I create a Repository? Use this preview() function somewhere else? Or Is it just a bad practice to do that? What's the best approach or way of thinking when we face this?

Or maybe I'm just missing something important in Laravel's ORM. :/


Solution

  • I assume Article is a model. So you have to add hasMany relation to User (user has many articles). Inside article you have to add preview function. In this case you will be able to find $user->article (or user->articles) and run ->preview function. This is the easiest solution I guess.

    You can also add custom attribute like getPreviewAttribute and append it to article model. This way you would have $user->article->preview.