I want to pass data from de setting table from the database to my layout view.
How do I get it done?
$item = Setting::find(1);
return view($this->controller.'/show')->with( 'item', $item);
Solution:
public function boot() {
if( !isset( $_SESSION['adminTitle'] ) ){
$item = Setting::find(1);
$item = $item->toArray();
$_SESSION['adminTitle'] = $item['title'];
$_SESSION['adminEmail'] = $item['email'];
$_SESSION['adminLogo'] = $item['logo'];
}
}
Why not simply this?:
// File app/Http/Controllers/ExampleController.php
//
class ExampleController extends Controller
{
public function show()
{
//
$setting = Setting::find(1);
return view('example', ['setting' => $setting]);
}
}
Within the Blade view:
<!-- resources/views/example.blade.php -->
{{ $setting->title }}
{{ $setting->logo }}
...
But, if you want to share settings between all your views, you can add this middleware:
// File app/Http/Middleware/ViewShareSettingMiddleware
//
class ViewShareSettingMiddleware
{
public function handle($request, Closure $next)
{
$setting = Setting::find(1);
view()->share('setting', $setting);
return $next($request);
}
}
Create your view in:
\resources\views\
Example: \resources\views\index.blade.php
$data['item'] = Setting::find(1);
return view('index')
->with( $data);
Or
$item = Setting::find(1);
return view('index', compact('item');
View: {{$item}}
Related
i have one project in CI3 and update for CI4
i have problem in my template, i receive Call to a member function get() on null.
my view not working call $this->traducao->get('search_string'); please help-me for update in class and libraries
My Function in Libraries
<?php
namespace App\Libraries;
use Config\Database;
class menus {
public $listMenus;
public $listSeo;
public function __construct(){
$this->set();
}
public function set(){
$db = Database::connect();
$builder = $db->table('menu');
$query = $builder->where("parente", 0)
->where("ativo", 1)
->orderBy('posicao', 'asc')
->get()->getResultArray();
if(is_array($query)){
$menusPai = $query;
}
$query2 = $builder->where("parente > 0")
->where("ativo", 1)
->orderBy('posicao', 'asc')
->get()->getResultArray();
if(is_array($query)){
$menusFilhos = $query2;
}
// $menusFilhos = ($query2->countAllResults() > 0) ? $query2->getResultArray() : false;
$menus = [];
foreach ($menusPai as $key => $value)
{
$this->listSeo[$value['link']]['pagina_titulo'] = $value['pagina_titulo'];
$this->listSeo[$value['link']]['pagina_keywords'] = $value['pagina_keywords'];
$this->listSeo[$value['link']]['pagina_description'] = $value['pagina_description'];
$menus[$value['id']]['filhos'] = [];
$menus[$value['id']]['dados'] = $value;
if ($menusFilhos)
{
foreach ($menusFilhos as $k => $v)
{
if ($v['parente'] == $value['id'])
{
$this->listSeo[$v['link']]['pagina_titulo'] = $v['pagina_titulo'];
$this->listSeo[$v['link']]['pagina_keywords'] = $v['pagina_keywords'];
$this->listSeo[$v['link']]['pagina_description'] = $v['pagina_description'];
$menus[$value['id']]['filhos'][] = $v;
}
}
}
}
$this->listMenus = $menus;
}
public function get(){
return $this->listMenus;
}
public function seo($tag){
$uri = new \CodeIgniter\HTTP\URI();
print_r($uri);
$uri = ($this->CI->uri->uri_string() == '') ? '/' : $this->CI->uri->uri_string();
return $this->listSeo[$uri][$tag];
// return $this->listSeo[$uri][$tag];
}
}
My ControllerBase
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Libraries\My_parser;
use App\Libraries\Preferencia;
use App\Models\index_model;
use App\Libraries\Traducao;
use App\Libraries\Menus;
class BaseController extends Controller
{
protected $helpers = [];
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
$this->_db = \Config\Database::connect();
$this->My_parser = new My_Parser();
$this->_model = new \App\Models\index_model();
$this->traducao = new Traducao();
}
public function output($data, $status){
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(
json_encode(
array(
'status'=> $status,
'response'=> $data
),
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
)
)->_display();
exit;
}
}
And my view
<div class="container">
<h2 class="text-center no-m"><?= $this->traducao->get('HOME_EMPRESAS_PARCEIRAS_TITULO') ?></h2>
and my index.php loading views layout
<?= $this->extend('template/head.php',array('css'=> $css, 'metatags'=> $metatags)) ?>
<?= $this->extend('template/header.php') ?>
<?= $this->extend('template/navbar.php') ?>
<?= $this->section('content')?>
<?= $this->endSection()?>
The short answer is it doesn't exist in the View because you never gave it to the View.
$this->traducao belongs to the Controller. It may have been constructed with the Controller but there's no immediate reason that any View would have access to it (or any data that wasn't passed directly to the View).
All incoming requests should be routed through Controllers; that is their most important purpose. Where is the Controller that's actually handling the request to your index.php file?
Any and all Views should be displayed by a Controller because that is where you have the ability to pass data (i.e. $this->traducao) into the View.
If this is actually CI4 as tagged, then you have a problem with CI3 code still being present as well; for example, $this->output isn't used to return Controller responses in CI4, it's $this->response instead.
I have made dynamic category routes by adding custom class to my app (how i did it is here) now i need to make my blade works with this dynamic path.
Logic
based on categories deeps my url will create such as:
site.com/category/parent
site.com/category/parent/child
site.com/category/parent/child/child
etc.
so far my view is just loading for site.com/category/parent for other urls it return 404 error.
code
CategoryRouteService
class CategoryRouteService
{
private $routes = [];
public function __construct()
{
$this->determineCategoriesRoutes();
}
public function getRoute(Category $category)
{
return $this->routes[$category->id];
}
private function determineCategoriesRoutes()
{
$categories = Category::all()->keyBy('id');
foreach ($categories as $id => $category) {
$slugs = $this->determineCategorySlugs($category, $categories);
if (count($slugs) === 1) {
$this->routes[$id] = url('category/' . $slugs[0]);
}
else {
$this->routes[$id] = url('category/' . implode('/', $slugs));
}
}
}
private function determineCategorySlugs(Category $category, Collection $categories, array $slugs = [])
{
array_unshift($slugs, $category->slug);
if (!is_null($category->parent_id)) {
$slugs = $this->determineCategorySlugs($categories[$category->parent_id], $categories, $slugs);
}
return $slugs;
}
}
CategoryServiceProvider
class CategoryServiceProvider
{
public function register()
{
$this->app->singleton(CategoryRouteService::class, function ($app) {
// At this point the categories routes will be determined.
// It happens only one time even if you call the service multiple times through the container.
return new CategoryRouteService();
});
}
}
model
//get dynamic slug routes
public function getRouteAttribute()
{
$categoryRouteService = app(CategoryRouteService::class);
return $categoryRouteService->getRoute($this);
}
blade
//{{$categoryt->route}} returning routes
<a class="post-cat" href="{{$category->route}}">{{$category->title}}</a>
route
//show parent categories with posts
Route::get('/category/{slug}', 'Front\CategoryController#parent')->name('categoryparent');
controller
public function parent($slug){
$category = Category::where('slug', $slug)->with('children')->first();
$category->addView();
$posts = $category->posts()->where('publish', '=', 1)->paginate(8);
return view('front.categories.single', compact('category','posts'));
}
Note: I'm not sure about this but i think i my route is kinda static! I mean it just getting 1 slug with it while my category can goes 2, 3 or 4 slug deep and it doesn't make sense to me to make several route and keep repeating Route::get('/category/{slug}/{slug}/{slug} like that.
As I said I'm not sure about this, please share your idea and solutions if you may.
UPDATE
based on Leena Patel answer I changed my route but when I get more than 1 slug in my url it returns error:
Example
route: site.com/category/resources (works)
route: site.com/category/resources/books/ (ERROR)
route: site.com/category/resources/books/mahayana/sutra (ERROR)
error
Call to a member function addView() on null
on
$category->addView();
when I comment that it returns error for $posts part. then error for my blade where i returned category title {{$category->title}}
So basically it seem doesn't recognize this function for returning view of category routes.
here is my function
public function parent($slug){
$category = Category::where('slug', $slug)->with('children')->first();
$category->addView();
$posts = $category->posts()->where('publish', '=', 1)->paginate(8);
return view('front.categories.single', compact('category','posts'));
}
any idea?
You can try using Route Pattern like below
Route::get('/category/{slug}', 'Front\CategoryController#parent')->where('slug','.+')->name('categoryparent')
So if you have more than one slugs in your url like /category/slug1/slug2
Your addView() method will work for one record and not for Collection So add foreach loop to achieve this.
public function parent($slug){
// $slug will be `slug1/slug2`
$searchString = '/';
$posts = array();
if( strpos($slug, $searchString) !== false ) {
$slug_array = explode('/',$slug);
}
if(isset($slug_array))
{
foreach($slug_array as $slug)
{
$category = Category::where('slug', $slug)->with('children')->first();
$category->addView();
$posts_array = $category->posts()->where('publish', '=', 1)->paginate(8);
array_push($posts,$posts_array);
}
}
else
{
$category = Category::where('slug', $slug)->with('children')->first();
$category->addView();
$posts = $category->posts()->where('publish', '=', 1)->paginate(8);
}
return view('front.categories.single', compact('category','posts'));
}
Hope it helps!
Documentation : https://laravel.com/docs/4.2/routing#route-parameters
Create route
Route::get('category/{cat}', 'YourController#mymethod');
Add this to your Providers/RouteServiceProvider.php 's boot method
public function boot()
{
Route::pattern('cat', '.+'); //add this
parent::boot();
}
In your method:
public function mymethod($cat){
echo $cat; //access your route
}
You can use optional URL sections in the route and use conditionals in controllers. Try this:
In your route:
Route::get('/category/{parent?}/{child1?}/{child2?}', 'Front\CategoryController#parent')->name('categoryparent');
In your controller:
public function mymethod($category, $parent, $child1, $child2){
if(isset($child2)){
//use $category, $parent, $child1, $child2 and return view
} else if(isset($child1)){
//use $category, $parent, $child1 and return view
} else if(isset($parent)){
//use $category, $parent and return view
} else {
//return view for $category
}
}
I have complex query and relation which I'm not fully understand. I'm kind of new in Laravel. Anyway, I'm looking for a way to load this with slugs instead of ID's.
This is the function in the controller
public function index( $category_id)
{
$Category = new Category;
$allCategories = $Category->getCategories();
$category = Category::find($category_id);
if($category->parent_id == 0) {
$ids = Category::select('id')->where('parent_id', $category_id)->where('parent_id','!=',0)->get();
$array = array();
foreach ($ids as $id) {
$array[] = (int) $id->id;
}
$items = Item::whereIn('category_id',$array)->where('published', 1)->paginate(5);
} else {
$items = Item::where('category_id' ,$category_id)->where('published', 1)->paginate(5);
}
return view('list', compact('allCategories','items'));
}
Those are relations in the Model
public function item()
{
return $this->hasMany('App\Item','category_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function getCategories()
{
$categoires = Category::where('parent_id',0)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function selectChild( $id )
{
$categoires = Category::where('parent_id',$id)->where('published', 1)->paginate(40);
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function addRelation( $categoires )
{
$categoires->map(function( $item, $key)
{
$sub = $this->selectChild($item->id);
$item->itemCount = $this->getItemCount($item->id , $item->parent_id );
return $item = array_add($item, 'subCategory', $sub);
});
return $categoires;
}
public function getItemCount( $category_id )
{
return Item::where('category_id', $category_id)->count();
}
This is what I have in my routes
Route::get('list/{category}', 'ListController#index')->name('list');
currently is loading urls like http://example.com/list/1 where 1 is the ID. I'm wonder if with current setup is possible to make it like, http://example.com/slug
I'm aware how slugs are working. I just can't understand how to use them in queries instead of ID's
You can use explicit Route Model Binding to grab your Category by slug before processing it.
In your RouteServiceProvider you need to bind the model:
Route::bind('category', function ($value) {
//Change slug to your column name
return App\Category::where('slug', $value)->firstOrFail();
});
Then, you can typehint the categories.
For example in your index method:
public function index(Category $category)
{
$Category = new Category;
$allCategories = $Category->getCategories();
//This line is obsolete now:
//$category = Category::find($category_id);
//...
}
Try to change your index function parameter from $category_id to $category_slug
Remove this line $Category = new Category;
And change this $category = Category::find($category_id);
To this: $category = Category::where('slug', $category_slug)->first();
*Assuming that you have a unique slug in category table
In Laravel 5, I am using simplePagination as outlined in the docs. I would like to customise the output so instead of double chevrons &rdaquo; '>>', I could put a right arrow. However I can't seen anywhere to customise it.
Does anyone know where the documentation for this is? Or where to begin looking?
While it is undocumented, it is certainly possible. It's pretty much the same as for Laravel 4. Basically all you need to is create a custom presenter and wrap the paginator instance.
Here's how a presenter might look like:
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Contracts\Pagination\Presenter;
use Illuminate\Pagination\BootstrapThreeNextPreviousButtonRendererTrait;
use Illuminate\Pagination\UrlWindow;
use Illuminate\Pagination\UrlWindowPresenterTrait;
class CustomPresenter implements Presenter
{
use BootstrapThreeNextPreviousButtonRendererTrait, UrlWindowPresenterTrait;
private $paginator;
private $window;
public function __construct(Paginator $paginator, UrlWindow $window = null)
{
$this->paginator = $paginator;
$this->window = is_null($window) ? UrlWindow::make($paginator) : $window->get();
}
public function render()
{
if ($this->hasPages()) {
return sprintf(
'<ul class="pagination">%s %s %s</ul>',
$this->getPreviousButton("Previous"),
$this->getLinks(),
$this->getNextButton("Next")
);
}
return null;
}
public function hasPages()
{
return $this->paginator->hasPages() && count($this->paginator->items() !== 0);
}
protected function getDisabledTextWrapper($text)
{
return '<li class="disabled"><span>'.$text.'</span></li>';
}
protected function getActivePageWrapper($text)
{
return '<li class="active"><span>'.$text.'</span></li>';
}
protected function getDots()
{
return $this->getDisabledTextWrapper("...");
}
protected function currentPage()
{
return $this->paginator->currentPage();
}
protected function lastPage()
{
return $this->paginator->lastPage();
}
protected function getAvailablePageWrapper($url, $page, $rel = null)
{
$rel = is_null($rel) ? '' : ' rel="'.$rel.'"';
return '<li><a href="'.htmlentities($url).'"'.$rel.'>'.$page.'</a></li>';
}
}
Then from your controller:
public function index()
{
$users = User::paginate(5);
$presenter = new CustomPresenter($users);
return view("home.index")->with(compact('users', 'presenter'));
}
The view:
#foreach ($users as $user)
<div>{{ $user->email }}</div>
#endforeach
{!! $presenter->render() !!}
What is the best way I could replace /controller/method/id in the URL with just /slug?
For example: trips/1 would become /honduras-trip
This is what I am doing but couldn't their be a better way?
My routes:
Route::get('/{slug}', 'HomeController#show');
My Controller:
public function show($slug)
{
$class = Slug::where('name', '=', $slug)->firstOrFail();
if($class->slugable_type == 'Trip')
{
$trip = Trip::find($class->slugable_id);
return $trip;
}
if($class->slugable_type == 'Project')
{
$project = Project::find($class->slugable_id);
return $project;
}
if($class->slugable_type == 'User')
{
$user = User::find($class->slugable_id);
return $user;
}
}
My Slug Model:
class Slug extends Eloquent {
public function slugable()
{
return $this->morphTo();
}
}
The other models all have this method:
public function slugs()
{
return $this->morphMany('Slug', 'slugable');
}
In your routes.php just give
Route::get('slug', array('uses' => 'HomeController#show'));
In your controller, write show() function
public function show() {
return View::make('welcome');
}
In your view give,
<li>slug</li>