我正在尝试构建一个应用程序,它将包含一个管理员仪表板,其中管理员将能够删除帖子,但他也将只能看到用户提交的帖子。 另一方面,客人将能够看到帖子,但他将能够创建用户提交的帖子。User使用Laravel提交的帖子
直到现在我已经设法让Posts functionallity工作,但不是用户提交的帖子。
我的控制器:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Usp;
class AdminUserPostsController extends Controller
{
public function index()
{
$userposts = Usp::orderBy('id', 'desc')->paginate(10);
return view('admin.userposts.archive')->withUsp($userposts);
}
public function show($id)
{
$userpost = Usp::find($id);
return view('admin.userposts.show')->withUsp($userpost);
}
}
我的模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Usp extends Model
{
//
}
我的档案查看
@extends('admin')
@section('dashboard-content')
<div class="col-md-8 offset-md-2">
<h1>Posts Archive</h1>
<hr>
</div>
@foreach ($userposts as $userpost)
<div class="col-md-6 offset-md-2">
<h3>Title: {{ $userpost->title }}</h3>
<hr>
</div>
@endforeach
@endsection
和我的路线(为特定的控制器)
Route::get('/admin/userposts', '[email protected]')->name('admin.userposts.archive');
Route::get('/admin/userposts/{id}', '[email protected]')->name('admin.userposts.show');
我收到userposts变量未定义的错误,虽然我在我的Controller中对其进行了定义。任何人都可以帮忙?
太感谢你了大家!也感谢您的解释。我的商店功能呢?当我必须重定向这个代码'返回重定向() - >路由('admin.userposts.show',$ userpost-> id);'我试图使'返回重定向() - >路由('管理员。 userposts.show',compact('userpost','id'));'但它不起作用:( –
路径函数的工作方式并不完全相同,对于显示帖子的简单内容,您可以传递值直接像'$ userpost-> id'一样,或者你可以去完整的对象,框架将决定它需要哪个值(默认为id)(即只给他'$ userpost')。如果你想要改变列,你可以改变[隐式绑定](https://laravel.com/docs/5.4/routing#implicit-binding)列。当你有几个参数时,你只需要传递一个数组,键是 –
此外,为了解释'compact('userpost','id')',这意味着你实际上有两个变量,一个是'$ userpost',另一个是'$ id'。你有他们这两个定义,它会返回'['userpost'=> $ userpost,'id'=> $ id]' –