【发布时间】:2019-08-15 14:09:31
【问题描述】:
我正在尝试使用最新版本的 laravel 构建一个类似博客的应用程序。我试图弄清楚如何从每篇文章的数据库中提取一个 slug,然后将其路由到所有工作正常。
我已经搞定了,但是如果您使用 slug 来查看,内容将不会显示在文章上。
localhost/articles/1 - 工作正常,页面上显示内容(标题等)
localhost/articles/installing-example - 这可行,但内容错误
当您尝试使用数据库中的 slug 导航到页面时会发生这种情况:Trying to get property 'title' of non-object (View: C:\xampp\htdocs\blogtest\resources\views\articles\show.blade.php)
此行出错:<h1><?php echo e($articles->title); ?></h1>
app/http/controllers/ArticlesController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Article;
class ArticlesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$articles = Article::all();
return view('articles.index')->with('articles', $articles);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$articles = Article::find($id);
return view('articles.show')->with('articles', $articles);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
app/Article.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $table = 'articles';
public $primaryKey = 'id';
public $timestamps = true;
}
路由/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::resource('articles', 'ArticlesController');
资源\视图\文章\show.blade.php
@extends('layouts.master')
@section('content')
<h1>{{$articles->title}}</h1>
@endsection
数据库
任何帮助和建议将不胜感激。
【问题讨论】:
标签: php laravel controller routes slug