Как я могу использовать динамический пользовательский шаблон 404 в Laravel?Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Как я могу использовать динамический пользовательский шаблон 404 в Laravel?

Сообщение Anonymous »

Я создаю приложение Laravel 8, поддерживающее темы. Активная тема задается в таблице настроек и родительский контроллер считывает ее оттуда:

Код: Выделить всё

class FrontendController extends Controller
{
protected $data;
protected $site_settings;
protected $theme_directory;
protected $site_name;
protected $tagline;
protected $owner_name;
protected $owner_email;
protected $twitter;
protected $facebook;
protected $instagram;
protected $is_cookieconsent;
protected $is_infinitescroll;
protected $pages;
protected $articles;
protected $article_categories;
protected $article_tags;
protected $authors;

public function __construct()
{
$this->site_settings = Settings::first();
$this->theme_directory = $this->site_settings['theme_directory'] ?? null;
$this->site_name = $this->site_settings['site_name'] ?? null;
$this->tagline = $this->site_settings['tagline'] ?? null;
$this->owner_name = $this->site_settings['owner_name'] ?? null;
$this->owner_email = $this->site_settings['owner_email'] ?? null;
$this->twitter = $this->site_settings['twitter'] ?? null;
$this->facebook = $this->site_settings['facebook'] ?? null;
$this->instagram = $this->site_settings['instagram'] ?? null;
$this->is_cookieconsent = $this->site_settings['is_cookieconsent'] ?? null;
$this->is_infinitescroll = $this->site_settings['is_infinitescroll'] ?? null;

// Most recent articles
$this->articles = Article::visible()->limit(5)->get();

// Article categories. Get only categories with articles
$this->article_categories = ArticleCategory::has('articles')->get();

// Pages
$this->pages = Page::all();

// Article tags
$this->article_tags = Tag::all();

// Authors
$this->authors = User::withCount('articles')
->having('articles_count', '>', 0)
->orderByDesc('articles_count')
->get();

$this->data = [
'theme_directory' => $this->theme_directory,
'site_name' => $this->site_name,
'tagline' => $this->tagline,
'owner_name' => $this->owner_name,
'owner_email' => $this->owner_email,
'twitter' => $this->twitter,
'facebook' => $this->facebook,
'instagram' => $this->instagram,
'is_cookieconsent' => $this->is_cookieconsent,
'is_infinitescroll' => $this->is_infinitescroll,
'pages' => $this->pages,
'articles' => $this->articles,
'categories' => $this->article_categories,
'tags' => $this->article_tags,
'authors' => $this->authors,
];
}
}
Controller ArticlesController, PagesController и т. д. расширяют указанный выше контроллер.
У меня есть собственный шаблон 404 для каждой темы. Путь к нему будет 'resources\views\themes\' .$theme_directory . '\templates\404.blade.php'.
Например, я показываю собственный шаблон 404 для отсутствующего тега следующим образом:

Код: Выделить всё

public function tag($tag_id)
{
$tag = Tag::firstWhere('id', $tag_id);

if ($tag) {
$articles = Article::visible()
->whereHas('tags', function (Builder $query) use ($tag) {
$query->where('id', $tag->id);
})
->paginate($this->per_page);

return view(
'themes/' . $this->theme_directory .  '/templates/index',
array_merge($this->data, [
'tag'      => $tag,
'articles' => $articles
])
);
}

return redirect('/404');
}
Но если я хочу показать это для отсутствующей статьи аналогичным образом, у меня ничего не получится, потому что я использую:

Код: Выделить всё

$article = Article::visible()->where('slug', $slug)->firstOrFail();

if(!$article) {
return redirect('/404');
};
Я нашел способ решить эту проблему:

Код: Выделить всё

$article = Article::visible()->where('slug', $slug)->first();

if(!$article) {
return redirect('/404');
};
но использование firstOrFail() является стандартом по уважительной причине, поэтому я бы предпочел его сохранить.
Как мне его сохранить

Код: Выделить всё

$article = Article::visible()->where('slug', $slug)->firstOrFail()
и использовать собственный шаблон ошибки 404? Существует ли «глобальное» решение для отображения 404.blade.php каждой темы для всех применимых случаев?

Подробнее здесь: https://stackoverflow.com/questions/797 ... in-laravel
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»