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
}
}
Related
I have 3 level deep categories in my laravel application like
Parent
- Child One
-- Child Two
When I use this nested categories in different parts such as menu, posts details etc. everything is just fine but recently I came cross an issue and I need guide to solve it.
The issue
If any of my posts includes child one or child two level category it's a bit hard to provide correct route path for it, EXAMPLE:
Parent route : site.com/p/slug
Child one route: site.com/parent_slug/childOne_slug
Child two route: site.com/parent_slug/childOne_slug/childTwo_slug
creating this much if statement in blade to make sure we get the right route for the right categories to me doesn't seem right. I was thinking about model function which returns final route depend on category parenting level in database but I wasn't sure if it's possible or not? and if it is, how?
Question
Is it possible I pass category routes to the categories from model?
How to do that?
Code
Category model
protected $fillable = [
'title', 'slug', 'thumbnail', 'publish','mainpage', 'parent_id', 'color', 'template'
];
public function posts(){
return $this->belongsToMany(Post::class, 'post_categories');
}
public function parent() {
return $this->belongsTo(Category::class, 'parent_id');
}
public function children() {
return $this->hasMany(Category::class, 'parent_id');
}
this is how currently i'm getting my posts categories:
#foreach($post->categories as $category)
<a class="post-cat" href="#">{{$category->title}}</a>
#endforeach
Any idea?
UPDATE
Well I solved it :-D here is the code I've made
public function getCatSlug(){
if($this->parent_id != ''){ //child one
if($this->parent->parent_id != ''){ //child two
if($this->parent->parent->parent_id != ''){ //child three
return $this->parent->parent->parent->slug. '/'. $this->parent->parent->slug. '/'. $this->parent->slug. '/'. $this->slug;
}
return $this->parent->parent->slug. '/'. $this->parent->slug. '/'. $this->slug;
}
return $this->parent->slug. '/'. $this->slug;
}
return $this->slug;
}
This does exactly what I needed it return slugs by orders like parent/child1/child2
Issue
the issue here is now routing this dynamic path as the result of this function I can now have any deep level of path and this needs to be dynamic in routes as well.
Route
my current route is like:
Route::get('/category/{slug}', 'Front\CategoryController#parent')->name('categoryparent');
which returns this path:
site.com/category/parent
but it doesn't return:
site.com/category/parent/child_one
site.com/category/parent/child_one/child_two
Controller
public function parent($slug){
$category = Category::where('slug', $slug)->with('children')->first();
$category->addView();
$posts = $category->posts()->paginate(8);
return view('front.categories.single', compact('category','posts'));
}
any idea?
Update 2
based on Matei Mihai answer I've made custom classes in App/Helpers folder with details below:
CategoryRouteService.php
<?php
namespace App\Helpers;
use App\Category;
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('p/' . $slugs[0]);
}
else {
$this->routes[$id] = url('/' . 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;
}
}
and CategoryServiceProvider.php
<?php
namespace App\Helpers;
use App\Helpers\CategoryRouteService;
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();
});
}
}
then I registered my provider to composer.json file like:
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers/CategoryServiceProvider.php" //added here
]
},
I also dumped autoloads and added this to my Category model
use App\Helpers\CategoryRouteService;
public function getRouteAttribute()
{
$categoryRouteService = app(CategoryRouteService::class);
return $categoryRouteService->getRoute($this);
}
then I used {{$category->route}} as my categries href attribute and I got this:
Argument 2 passed to App\Helpers\CategoryRouteService::determineCategorySlugs() must be an instance of App\Helpers\Collection, instance of Illuminate\Database\Eloquent\Collection given
which is refers to:
private function determineCategorySlugs(Category $category, Collection $categories, array $slugs = [])
{
ideas?
It is possible, but you must take care of the script performance because it could end up having a lot of DB queries done to determine each category route.
My recommendation would be to create a CategoryRouteService class which will be registered as singleton to keep the database queries as low as possible. It could be something like:
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('/p/' . $slugs[0]);
}
else {
$this->routes[$id] = url('/' . 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;
}
}
Now as I said before, you need a service provider to register this service. It should look like this:
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();
});
}
}
This service provider must be added in the app configuration file.
The Category model could have a method which defines the route attribute:
class Category extends Model
{
public function getRouteAttribute()
{
$categoryRouteService = app(CategoryRouteService::class);
return $categoryRouteService->getRoute($this);
}
/** Your relationships methods **/
}
Finally, you can use it in your blade views simply by using $category->route.
#foreach($post->categories as $category)
<a class="post-cat" href="{{$category->route}}">{{$category->title}}</a>
#endforeach
Please note that there could be other solutions better than this. I just came across this one without thinking too much. Also, the code above was not tested so please be aware that it might need some minor changes to make it work properly.
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
I need a little guidance here. I'm using Codeigniter 3.
Since it is MVC fw with segment routing, I want to know how is possible to create custom route which will show just a name of record (it can be category, product, post etc..) returned from database instead of id/name when I need id segment to identify which record from database I need to return or preview by that id.
I will post some code example:
Controller
class Categories extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('CategoryM');
}
public function index(){
$data = array(
'category_list' => $this->CategoryM->listAll()
);
$this->load->view('test/category_list', $data);
}
public function preview()
{
$categoryId = $this->uri->segment(2);
$data = array (
'previewByCategory' => $this->CategoryM->previewByCategory($categoryId)
);
$this->load->view('public/preview_by_category', $data);
}
Model
<?php
class CategoryM extends CI_Model {
public function listAll() {
$query = $this->db
->select('*')
->from('categories')
->where('parentid', NULL, TRUE)
->order_by('name', 'asc')
->get();
if($query->num_rows() > 0) {
return $query->result();
}else{
return false;
}
public function previewByCategory($categoryId=''){
$query = $this->db
->select( /* posts and categories data */ )
->from('categories')
->join('posts', 'posts.categoryID = categories.id', 'left')
->where('categories.id', $categoryId)
->get();
if( $query->num_rows() > 0 ){
return $query->result();
}else{
return false;
}
}
}
View
<?php if($category_list):?>
<?php foreach($category_list as $category):?>
<h3>
<a href="<?php echo base_url() . strtolower(url_title($category->name) . '/' . $category->id);?>">
<?php echo $category->name;?>
</a>
</h3>
<?php endforeach;?>
<?php endif;?>
My Routes
// Category routes
$route['categories'] = 'categories/index';
$route['(:any)/(:num)'] = 'categories/preview/$1';
What I want is instead of routes
www.mywebsite/categoryname/categoryid/
to display just
www.mywebsite/categoryname
which will list all products from that category group. But how to do this without id in url. I'm sorry if my question is too broad. Thank's in advance.
Codeigniter does not allow you to get database access in routes.
but you can create the database instance manually.
routes.php
$slug= ($this->uri->segment(1)) ? $this->uri->segment(1) : false;
if($slug){
//include your database
require_once(BASEPATH."/database/DB.php");
$db=& DB();
$category = $this->db
->select('name')
->from('categories')
->where('parentid', NULL, TRUE)
->where('name',$slug)
->get()->row();
if($category){
//$category->name must be unique in database
$route[$category->name] = 'categories/index';
}
}
In Categories controller
class Categories extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('CategoryM');
}
public function index(){
echo $category_name=$this->uri->segment(1);
}
}
URL
www.mywebsite/categoryname
//if categoryname exist in category
output :
categoryname
First you have to add column to your category table say url_title, which is unique and validate as a URI. Then you have to modify your route.php
// Category routes
$route['categories'] = 'categories/index';
$route['(:any)'] = 'categories/$1'; // $1 pass the utl_title value to Categories/preview($url_title)
and your controller
public function preview($url_title=null) {
$categoryId = $this->uri->segment(2);
$data = array (
'previewByCategory' => $this->CategoryM->previewByCategory($url_title)
);
$this->load->view('public/preview_by_category', $data);
}
and your model
public function previewByCategory($url_title=''){
$query = $this->db
->select( /* posts and categories data */ )
->from('categories')
->join('posts', 'posts.categoryID = categories.id', 'left')
->where('categories.url_title', $url_title)
->get();
if( $query->num_rows() > 0 ){
return $query->result();
}else{
return false;
}
}
I hope this would work for you. Please be carefull my posted code will have syntax errors because I did not tested it.
How can I create a nested list of categories in Laravel?
I want to create something like this:
--- Php
------ Laravel
--------- Version
------------ V 5.7
--- Python
------ Django
--- Ruby
..........
The fields of my categories table are:
id | name | parent_id
If I have to add another column like depth or something, please tell me.
I am using this following code, but I think it is not the best solution. Besides, I can not pass this function to my view.
function rec($id)
{
$model = Category::find($id);
foreach ($model->children as $chield) rec($chield->id);
return $model->all();
}
function main () {
$models = Category::whereNull('parent_id')->get();
foreach ($models as $parent) return rec($parent->id);
}
You can make a self-referential model:
class Category extends Model {
public function parent()
{
return $this->belongsTo('Category', 'parent_id');
}
public function children()
{
return $this->hasMany('Category', 'parent_id');
}
}
and make a recursive relation:
// recursive, loads all descendants
public function childrenRecursive()
{
return $this->children()->with('childrenRecursive');
}
and to get parents with all their children:
$categories = Category::with('childrenRecursive')->whereNull('parent_id')->get();
Lastly you need to just iterate through the children until children is null. There can definitely be some performance issues with this if you are not careful. If this is a fairly small dataset that you plan to remain that way it shouldn't be an issue. If this is going to be an ever growing list it might make sense to have a root_parent_id or something to query off of and assemble the tree manually.
This function will return tree array:
function getCategoryTree($parent_id = 0, $spacing = '', $tree_array = array()) {
$categories = Category::select('id', 'name', 'parent_id')->where('parent_id' ,'=', $parent_id)->orderBy('parent_id')->get();
foreach ($categories as $item){
$tree_array[] = ['categoryId' => $item->id, 'categoryName' =>$spacing . $item->name] ;
$tree_array = $this->getCategoryTree($item->id, $spacing . '--', $tree_array);
}
return $tree_array;
}
If someone needs a better answer look up my answer, it helped me, when I had faced with such a problem.
class Category extends Model {
private $descendants = [];
public function subcategories()
{
return $this->hasMany(Category::class, 'parent_id');
}
public function children()
{
return $this->subcategories()->with('children');
}
public function hasChildren(){
if($this->children->count()){
return true;
}
return false;
}
public function findDescendants(Category $category){
$this->descendants[] = $category->id;
if($category->hasChildren()){
foreach($category->children as $child){
$this->findDescendants($child);
}
}
}
public function getDescendants(Category $category){
$this->findDescendants($category);
return $this->descendants;
}
}
And In your Controller just test this:
$category = Category::find(1);
$category_ids = $category->getDescendants($category);
It will result ids in array all descendants of your category where id=1.
then :
$products = Product::whereIn('category_id',$category_ids)->get();
You are welcome =)
Searching for something somehow in this area I wanted to share a functionality for getting the depth level of child:
function getDepth($category, $level = 0) {
if ($category->parent_id>0) {
if ($category->parent) {
$level++;
return $this->getDepth($category->parent, $level);
}
}
return $level;
}
Maybe it will help someone!
Cheers!
you can solve this problem like this :
class Category extends Model
{
public function categories()
{
return $this->hasMany(Category::class);
}
public function childrenCategories()
{
return $this->hasMany(Category::class)->with('categories');
}
}
and get category with children like this :
Category::whereNull('category_id')
->with('childrenCategories')
->get();
notice : just rename parent_id column to category_id
This also worked:
View:
$traverse = function ($categories) use (&$traverse) {
foreach ($categories as $category) $traverse($cat->Children);
};
$traverse(array ($category));
Model:
public function Children()
{
return $this->hasMany($this, 'parent');
}
public function Parent()
{
return $this->hasOne($this,'id','parent');
}
I am trying to use ajax smart search,
http://maxoffsky.com/code-blog/laravel-shop-tutorial-3-implementing-smart-search/
But my application can not find the controller I used from the tutorial above.
This is the error i get:
Class App\Http\Controllers\Api\ApiSearchController does not exist
After googling this error message I found out that it is caused by an incorrect route. But I believe I set my routes correctly.
This is my route:
Route::get('api/search', 'Api\ApiSearchController#index');
And here is my controller:
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Base\Controller;
class ApiSearchController extends Controller {
public function appendValue($data, $type, $element)
{
// operate on the item passed by reference, adding the element and type
foreach ($data as $key => & $item) {
$item[$element] = $type;
}
return $data;
}
public function appendURL($data, $prefix)
{
// operate on the item passed by reference, adding the url based on slug
foreach ($data as $key => & $item) {
$item['url'] = url($prefix.'/'.$item['slug']);
}
return $data;
}
public function index()
{
$query = e(Input::get('q',''));
if(!$query && $query == '') return Response::json(array(), 400);
$products = Product::where('published', true)
->where('name','like','%'.$query.'%')
->orderBy('name','asc')
->take(5)
->get(array('slug','name','icon'))->toArray();
$categories = Category::where('name','like','%'.$query.'%')
->has('products')
->take(5)
->get(array('slug', 'name'))
->toArray();
// Data normalization
$categories = $this->appendValue($categories, url('img/icons/category-icon.png'),'icon');
$products = $this->appendURL($products, 'products');
$categories = $this->appendURL($categories, 'categories');
// Add type of data to each item of each set of results
$products = $this->appendValue($products, 'product', 'class');
$categories = $this->appendValue($categories, 'category', 'class');
// Merge all data into one array
$data = array_merge($products, $categories);
return Response::json(array(
'data'=>$data
));
}
}
I think the namespace you specified isn't the one expected :
Class App\Http\Controllers\Api\ApiSearchController does not exist
doesn't match :
<?php namespace App\Http\Controllers;