1 回答

TA貢獻1851條經驗 獲得超3個贊
好的,我將在這里做出一些假設,但假設您的設計模型上有這個函數:
設計.php
class Design extends Model
{
...
/**
* Assuming you dont have a slug column on your designs table
*
* Also assuming the slug is built from a column called 'name' on
* your designs table
*/
public function getSlugAttribute()
{
return \Illuminate\Support\Str::slug($this->name);
}
// This assumes there is a column on posts table of 'design_id'
public function posts()
return $this->hasMany(Post::class);
}
...
}
現在讓我們舉例說明如何構建所需的路線。
編輯
通過與提問者進一步討論,他們不想顯示與他們所展示的設計相關的所有帖子(參見上面的模型)。這個答案中的設置適合于此,您可以參考下面定義的 show 方法。假設我們有DesignsController.php:
class DesignsController extends Controller
{
...
public function index()
{
return view('designs.index', [
'designs' => Design::all(),
]);
}
public function show(Request $request, string $design)
{
// It is worth noting here if name has a double space you wont
// be able to build backwards to it for a query
// ie) Design\s\sOne !== $lower(Design\sOne)\
$spaced = str_replace('-', ' ', $design);
$lower = strtolower($spaced);
$design = Design::with('posts')->whereRaw("LOWER(name) = '$lower'")->first();
return view('designs.show', [
'design' => $design,
]);
}
...
}
現在,在“designs/index.blade.php”文件中,您可以執行以下操作:
@foreach($designs as $design)
<a href="{{ route('designs.show', [ 'design' => $design->slug ]) }}">{{ $design->name }}</a>
@endforeach
這將按名稱列出您的所有設計,并通過其 slug 鏈接到 designs.show 路線。
如果您始終希望在序列化為數組或 json時加載 slug 值,則可以將其添加到模型上受保護的 $appends 數組中。
如果您不總是希望附加它,則需要在運行時使用例如$design->append('slug').
或者,如果您有一系列設計,您也可以這樣做$designs->each->append('slug')。
現在,在您的 designs.show Blade 文件中,您可以使用我們使用 Design::with('posts') 加載的關系訪問設計的帖子,方法如下:
@foreach ($design->posts as $post)
<img src="{{ asset('storage/'.$post->postImage) }}">
@endforeach
- 1 回答
- 0 關注
- 177 瀏覽
添加回答
舉報