Skip to content

Instantly share code, notes, and snippets.

@corazzi
Last active January 24, 2017 10:23
Show Gist options
  • Save corazzi/e8d32557a2b6c78df5e8aa42e3aa0e76 to your computer and use it in GitHub Desktop.
Save corazzi/e8d32557a2b6c78df5e8aa42e3aa0e76 to your computer and use it in GitHub Desktop.
Use view namespaces in Laravel controllers
<?php
/**
* Return a view under the controller's view namespace if one is set
*
* @param string $template
* @param array $data
* @param array $mergeData
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function view(string $template, array $data = [], array $mergeData = [])
{
if ($this->hasViewNamespace() && $this->namespacedViewExists($template)) {
return $this->namespacedView($template, $data, $mergeData);
}
return view($template, $data, $mergeData);
}
/**
* Check if the controller has a view namespace
*
* @return bool
*/
private function hasViewNamespace() : bool
{
return isset($this->viewNamespace);
}
/**
* Assert that the template under the controller's view namespace exists
*
* @param $template
*
* @return bool
*/
private function namespacedViewExists(string $template) : bool
{
return view()->exists(
$this->buildNamespacedViewPath($template)
);
}
/**
* Return the requested template under the controller's view namespace
*
* @param string $template
* @param array $data
* @param array $mergeData
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
private function namespacedView(string $template, array $data = [], array $mergeData = [])
{
return view(
$this->buildNamespacedViewPath($template),
$data,
$mergeData
);
}
/**
* Build the path for the specified template under the controller's view namespace
*
* @param $template
*
* @return string
*/
private function buildNamespacedViewPath(string $template) : string
{
return sprintf('%s.%s', $this->viewNamespace, $template);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment