使用slug后检索数据时出错(Laravel 5.3)

时间:2016-11-12 07:39:42

标签: laravel laravel-5

我在访问使用slug url的页面时遇到问题,以前刚刚使用id时它运行得很好。

路线:Route::get('journal/{journalslug}', 'JournalController@show');

网址:href="{{ url('journal/' . $journal->journalslug) }}

控制器:

public function show($journalslug) {
        $journal = Journal::where('journalslug','=',$journalslug)->get();
        return view('journal/show', compact('journal', $journal));
    }

查看:

<div class="large-widget m30">
                    <div class="post-desc">
                        <h2 style="text-align: center;">{{ $journal->title }}</h2>
                        <p style="text-align: center;"><strong>
                                @foreach($journal->user as $item)
                                {{ $item->name }},
                                @endforeach
                        </strong></p>
                        <p style="text-align: center;"><strong>Abstract :</strong></p>
                        <p>{!! $journal->abstract !!}</p>
                        <p style="text-align: center;"><a href="{{ asset('jurnal/' . $journal->file) }}" style="color : #00569d;">View Journal</a></p>
                    </div><!-- end post-desc -->
                </div><!-- end large-widget -->

错误:

Undefined property: Illuminate\Database\Eloquent\Collection::$title (View: C:\xampp\htdocs\2mark\resources\views\journal\show.blade.php)

我不知道自己做错了什么,需要你的帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

将其更改为:

<?php

include('simple_html_dom.php');
$filename='index.php';
$html = file_get_html($filename);

$h3 = array();
foreach ($html->find('h3') as $element) {
    $h3[] = $element->innertext;
}

$p = array();
foreach ($html->find('p') as $element) {
    $p[] = $element->innertext;
}

for ($i = 0; $i <= count($h3); $i++) {
    ?>
    <div class = "form-group">
        <label class = "control-label col-sm-2" for = "pwd">H3</label>
        <div class = "col-sm-10">
            <input type = "text" class = "form-control" name = "h3[$i]" id = "h3[$i]" value = "<?php echo $h3[$i] ?>">
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-sm-2" for="pwd">Paragraph</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="p[$i]" name="p[$i]" value="<?php echo $p[$i] ?>">
        </div>
    </div>
    <?php
}

答案 1 :(得分:0)

您应该让我们firstOrFail()让您解决问题:

public function show($journalslug) {
    try {
        $journal = Journal::where('journalslug','=',$journalslug)->firstOrFail();
        return view('journal/show', compact('journal', $journal));
    } catch(Illuminate\Database\Eloquent\ModelNotFoundException $e) {
        // catch exception here
    }
    // return error page - no results found
}
  

firstOrFail方法将检索第一个结果   查询;但是,如果没有找到结果,a   Illuminate\Database\Eloquent\ModelNotFoundException将被抛出。

如果你没有找到任何结果,这将确保你,希望这会有所帮助。