2 回答

TA貢獻1821條經驗 獲得超6個贊
我認為你很接近,但我有一些想法可能對你有幫助。
首先,您是否檢查過您的路線設置是否正確routes/web.php?如果您使用了 Laravel 文檔中的一些示例,則您的路由可能會在不使用您編寫的控制器的情況下返回視圖。如果你有這樣的事情:
Route::get('/', function () {
return view('dashboard');
});
...那么你可能想用這樣的東西替換它:
Route::get( '/', 'PostController@show );
管理路由的方法有很多種——Laravel Docs會很好地解釋其中的一些。
此外,當將東西從控制器傳遞到視圖時,我喜歡將我的對象分配給關聯數組,然后在使用視圖方法時傳遞該數組。這完全是個人喜好,但您可能會發現它很有用。有點像這樣:
public function show()
{
// Create output array - store things in here...
$output = [];
$output[ "posts" ] = Post::all();
// Render the Dashboard view with data...
return view( 'dashboard', $output );
}
希望有些幫助!

TA貢獻1963條經驗 獲得超6個贊
試試下面的代碼,
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Post;
use App\UserTypes;
use Auth;
use Hashids;
use Redirect;
use Illuminate\Http\Request;
use Hash;
class PostController extends Controller
{
public function show()
{
//Fetching all the posts from the database
$posts = Post::get();
return view('dashboard', compact('posts'));
}
public function store(Request $request)
{
$this->validate($request,[
'body' => 'required'
]);
$post = new Post;
$post->body = $request->body;
$request->user()->posts()->save($post);
return redirect()->route('dashboard');
}
}
- 2 回答
- 0 關注
- 140 瀏覽
添加回答
舉報