我正在嘗試構建一個應用程序,它將包含一個管理員儀表板,其中管理員將能夠刪除帖子,但他也將只能看到用戶提交的帖子。 另一方面,客人將能夠看到帖子,但他將能夠創建用戶提交的帖子。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]' –