【问题标题】:laravel getting dynamic view based on urllaravel 获取基于 url 的动态视图
【发布时间】:2019-04-06 07:59:52
【问题描述】:

我已经通过向我的应用程序 (how i did it is here) 添加自定义类来制作动态类别路由,现在我需要让我的刀片使用这个动态路径。

逻辑

基于我的 url 将创建的深度类别,例如:

site.com/category/parent
site.com/category/parent/child
site.com/category/parent/child/child
etc.

到目前为止,我的视图只是为 site.com/category/parent 加载其他 URL,它返回 404 错误。

代码

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'));
}

注意:我不确定这一点,但我认为我的路线有点静态!我的意思是它只会得到 1 个 slug,而我的类别可以深入 2、3 或 4 个 slug,对我来说,走多条路线并像这样不断重复 Route::get('/category/{slug}/{slug}/{slug} 是没有意义的。

正如我所说,我对此不确定,如果可以,请分享您的想法和解决方案。

更新

基于Leena Patel 的回答,我更改了路线,但是当我的网址中出现超过 1 个 slug 时,它返回错误:

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

$category->addView();

当我评论它返回 $posts 部分的错误时。然后我的刀片出错,我返回类别标题{{$category-&gt;title}}

所以基本上它似乎无法识别返回类别路线视图的此功能。

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'));
}

有什么想法吗?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以尝试使用如下所示的路由模式

    Route::get('/category/{slug}', 'Front\CategoryController@parent')->where('slug','.+')->name('categoryparent')
    

    因此,如果您的网址中有多个 slug,例如 /category/slug1/slug2

    您的 addView() 方法适用于 one record 而不适用于 Collection 所以添加 foreach 循环来实现这一点。

    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'));
    }
    

    希望对你有帮助!

    文档:https://laravel.com/docs/4.2/routing#route-parameters

    【讨论】:

    【解决方案2】:

    您可以在路由中使用可选的 URL 部分并在控制器中使用条件。试试这个:

    在您的路线

    Route::get('/category/{parent?}/{child1?}/{child2?}', 'Front\CategoryController@parent')->name('categoryparent');
    

    在您的控制器中:

    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
        }
    
    }
    

    【讨论】:

    • 所以如果我这样做/category/{parent?}/{child1?}/{child2?} 并且我的网址只包含parent 部分会出现问题吗?
    • /category/{parent?}/{child1?}/{child2?} 表示始终需要 category。所以如果你的url包含parent,你必须提供category,这样就可以了。
    【解决方案3】:

    创建路线

    Route::get('category/{cat}', 'YourController@mymethod');
    

    将此添加到您的 Providers/RouteServiceProvider.php 的启动方法中

    public function boot()
    {
        Route::pattern('cat', '.+'); //add this
    
        parent::boot();
    }
    

    在你的方法中:

    public function mymethod($cat){
        echo $cat;  //access your route
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-28
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      相关资源
      最近更新 更多