【问题标题】:Making dynamic pages from DB with Laravel使用 Laravel 从 DB 制作动态页面
【发布时间】:2014-10-29 14:11:23
【问题描述】:

目前我正在获取表格中的所有行,并在页面上显示每个类别。现在我想做一些新的东西,但是在尝试了一些东西之后我有点卡住了。 所以现在我有一个名为“照片”的链接,当点击它时,所有的照片都会显示出来。现在我想要一个子菜单,这样我就只能看到某个类别的照片。这就是表格的样子

pk  imgUrl  category
--------------------
1   ...     portret
2   ...     nature
3   ...     portret
4   ...     cars

导航到 www.mysite.com/photos 时,无论类别如何,都会显示我的所有照片。 现在我想在访问 www.mysite.com/photos/portret 时添加我只看到来自 portret 类别的照片的功能。

我能够动态创建链接,它们会转到正确的 URL (www.mysite.com/photos),但页面是空的。所以我不知道出了什么问题。路由?

我将在下面发布我尝试过的和目前拥有的。

在导航之前是静态的,但现在我希望它是动态的,我添加了 NavController

public function index()
{
    //
    //return Photo::all();
    $title = "Photo";
    $photos = Photo::orderBy('category')->get();
    return View::make('photo')->with('title', $title)->with('photos', $photos);

    //QUERY - Eloquent
    //return Photo::all();
}

它的对应视图是 nav.blade 包含这个(这打印出我的动态链接)

<?php 
    $category = "";
?>
<ul>
    @foreach($photos as $photo)
        @if($category != $photo->Category)
            <li><a href="{{ $photo->Category }}"> {{ $photo->Category }} </a></li>
            <?php $category = $photo->Category; ?>
        @endif
    @endforeach
</ul>

然后在我的路线中,我可以导航到动态页面

Route::get('photos/{theme}', array('as' => '{theme}', 'uses' => 'PhotosController@show'));

然后在我的 PhotosController 我有

    public function show($theme){
        $photos = Photo::where('category', $theme);
        return View::make('photo')->with('title', $theme)->with('photos', $photos);
    }

在我看来 photos.blade

    <?php 
        $category = ""; 
    ?>
    @foreach($photos as $photo)
        <a href="#myModal" class="linkWrapper"> {{ HTML::image("img/$photo->Link", "$photo->Title", array("class"=>"thumbnail thumbEffect")) }} </a>
    @endforeach

所以我没有看到或理解我做错了什么。此外,当转到页面 www.mysite.com/photos/portret 时,动态链接不再出现,而这应该只是在包含在我的模板中的 nav.blade 中。 有人可以帮帮我吗?

编辑:我在这里的大部分工作都是由于我在 SO 上找到的另一个 Q/A,这就是 Laravel Creating Dynamic Routes to controllers from Mysql database

【问题讨论】:

    标签: php dynamic laravel routing


    【解决方案1】:

    您的代码在我看来几乎不错,但您忘记从数据库中获取照片:

    public function show($theme)
    {
        $photos = Photo::where('category', $theme)->get(); /// here
    
        return View::make('photo')->with('title', $theme)->with('photos', $photos);
    }
    

    【讨论】:

    • 谢谢!如果你一遍又一遍地查看相同的代码,很容易错过一些东西。添加 get() 确实是解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 2016-03-05
    相关资源
    最近更新 更多