User Submitted Posts using Laravel

不羁岁月 提交于 2019-12-24 07:37:19

问题


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.

My Controller:

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);
    }
}

My Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Usp extends Model
{
    //
}

My Archive View

@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');

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


回答1:


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);

To this

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

How does it work :

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

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

And the with just transmits all the array to the view

PS :

compact('userposts')

Is exactly the same as this

['userposts' => $userposts]



回答2:


If you want to use userposts variable, do this:

return view('admin.userposts.archive', compact('userposts');

Or this:

return view('admin.userposts.archive', ['userposts' => $userposts]);



回答3:


Change this:

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

to

return view('admin.userposts.show', array('userpost' => $userpost));

and try again. You can get $userpost on blade view like:

{{ $userpost }}

If it is an array, use foreach() to get all of its elements.



来源:https://stackoverflow.com/questions/43455324/user-submitted-posts-using-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!