Laravel how do i pass relationship in title?
This is what i have:
public function show($categoty, $post) {
$post = Post::where([ ['slug', '=', $post]->firstOrFail();
$title = $post->category->name;
return view('home.chords.show', compact('chord', 'title'));
}
This code works... it gets the Category name in title.. My question is how do i pass the post title with the category name?
what i want to show in $title is
Category Name - Post Title
Thank you in advance
CodePudding user response:
You can use string concatenation like this:
$title = $post->category->name . ' - ' . $post->title;
You can also use string interpolation, like this:
$title = "{$post->category->name} - {$post->title}";
An other way to achieve this would be to add an accessor in your Post model like this :
// Inside Post Model
public function getCategoryTitleLabelAttribute()
{
return "{$this->category->name} - {$this->title}";
}
// Anywhere in your app:
$post->category_title_label;