User Submitted Posts using Laravel

2019-07-29 20:02发布

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 ?

3条回答
爷、活的狠高调
2楼-- · 2019-07-29 20:14

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楼-- · 2019-07-29 20:16

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.

查看更多
The star\"
4楼-- · 2019-07-29 20:23

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]
查看更多
登录 后发表回答