0
votes

I am a newbe in Laravel. The docs show how to use relationships like this: One To Many (Inverse) / Belongs To Now that we can access all of a post's comments, let's define a relationship to allow a comment to access its parent post. To define the inverse of a hasMany relationship, define a relationship method on the child model which calls the belongsTo method:


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Once the relationship has been defined, we can retrieve a comment's parent post by accessing the post "dynamic relationship property":

use App\Models\Comment;

$comment = Comment::find(1);

return $comment->post->title;

My question is: Where is this code? In a controller or in a view?

2

2 Answers

0
votes

If you use MVC structure, you should understand that

Model is layer where you store your data

View is layer where you should only display your data

and Controller is layer where you can keep your logic.

If you have a lot of difficult logic or big application, you should better to use Services, as layer between Controllers And Models.

Receiving Comments from model and prepeare them should be in controller level. In view level you just define how to show them to user.

I hope it will help you to understand difference between logic layers.

0
votes

you can access this relationship in controller or view like this-

suppose you want to make relation between product model and brand model:-

in product model:-

public function brand(){
    return $this->belongsTo('App\Model\Brand','brand_id','id');
}

now you are able to see which product belongs to which brand without any query or using loop. just do in controller:-

$product=Product::with('brand')->get();

here you get all the data...

and when you use it on **view **just do it:

{{$product->brand->brand_name}}

//brand name should the column name

I hope you understood... Happy Learning!