用户使用Laravel提交的帖子 [英] User Submitted Posts using Laravel

查看:76
本文介绍了用户使用Laravel提交的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个应用程序,该应用程序将包含一个管理仪表板,管理员可以在其中管理CRUD帖子,但他也只能查看用户提交的帖子. 另一方面,来宾只能看到帖子,但可以创建用户提交的帖子.

I am trying to build an application wich it will contain an admin dashboard where the admin will be able to CRUD Posts but also he will be able just to see User Submitted Posts. On the other hand the guest will be able to just see the Posts, but he will be able to Create User Submitted Posts.

到目前为止,我已经设法使帖子"功能正常运行,但对于用户提交的帖子"却无法正常工作.

Until now I have managed to get the Posts functionallity working, but not for the User Submitted Posts.

我的控制器:

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

和我的路线"(针对特定控制器)

and My Routes(for the specific controller)

Route::get('/admin/userposts', 'AdminUserPostsController@index')->name('admin.userposts.archive');
Route::get('/admin/userposts/{id}', 'AdminUserPostsController@show')->name('admin.userposts.show');

我收到未定义userposts变量的错误,尽管我在Controller中定义了该变量.有谁可以帮助您?

I am getting the error that userposts variable is not defined, although I define it in my Controller. Anyone that can help ?

推荐答案

您应该将变量传输"到视图中.有几种方法可以做到这一点,但我想说的是最常见的是使用"with compact".在您的情况下,您应该更改此

You should "transmit" your variables to your view. There are several ways to do this, but I'd say the most common is to use the "with compact". In your case, you should change this

return view('admin.userposts.archive')->withUsp($userposts);

对此

return view('admin.userposts.archive')->with(compact('userposts'));

工作方式:

compact("varname", [...])

返回一个数组,键为变量名,值为变量值

returns an array with the keys being the variable name and the values being the variable values

并且with只是将所有数组传输到视图

And the with just transmits all the array to the view

PS:

compact('userposts')

与此完全相同

['userposts' => $userposts]

这篇关于用户使用Laravel提交的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆