2016-09-24 2 views
-1

Я получаю сообщение об ошибке в laravel 5.3.9 на панели инструментов с неопределенными сообщениями переменной. Я пытаюсь перечислить все сообщения от пользователя, которое у него есть в базе данных. Вот мой код до сих пор:Laravel undefined variable in view file

UserController.php

<?php 

namespace App\Http\Controllers; 

use App\User; 
use Illuminate\Http\Request; 
use Illuminate\Support\Facades\Auth; 


class UserController extends Controller 
{ 
    public function postSignUp(Request $request) 
    { 
     // Validate the entry of the sign up form 
     $this->validate($request, [ 
      'email'  => 'email | required | unique:users', 
      'first_name' => 'required | max:120', 
      'password' => 'required | min:6' 
     ]); 

     $email = $request['email']; 
     $first_name = $request['first_name']; 
     $password = bcrypt($request['password']); 

     $user = new User(); 
     $user->email = $email; 
     $user->first_name = $first_name; 
     $user->password = $password; 

     $user->save(); 

     Auth::attempt($user); 

     return redirect()->route('dashboard'); 

    } 

    public function postSignIn(Request $request) 
    { 
     // Validate the sign in form 
     $this->validate($request, [ 
      'email'  => 'email | required', 
      'password' => 'required | min:6' 
     ]); 

     if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) { 
      return view('dashboard'); 
     } 

     return redirect()->back(); 
    } 
} 

?> 

PostController.php

<?php 

namespace App\Http\Controllers; 

use App\Post; 
use Illuminate\Http\Request; 

class PostController extends Controller 
{ 
    public function getDashboard() 
    { 
     $posts = Post::all(); 
     return view('dashboard', [ 'posts' => $posts ]); 
    } 

    public function postCreatePost(Request $request) 
    { 
     // Validate the post text field 
     $this->validate($request, [ 
      'body' => 'required | max:1000' 
     ]); 

     $post = new Post(); 
     $post->body = $request['body']; 
     $message = "There was an error"; 

     if($request->user()->posts()->save($post)) { 
      $message = "Post succesfully created"; 
     } 
     return redirect()->route('dashboard')->with([ 'message' => $message ])->compact($posts); 
    } 

    public function getDeletePost($post_id) 
    { 
     $post = Post::where('id', $post_id)->first(); 
     $post->delete(); 

     return redirect()->route('dashboard')->with(['message' => 'Post succesfully deleted']); 
    } 
} 

dashboard.blade.php

@foreach($posts as $post) 
     <article class="post"> 
      <p>{{ $post->body }}</p> 
      <div class="info"> 
       Posted by {{ $post->user->first_name }} on {{ $post->user->created_at }} 
      </div> 
      <div class="interaction"> 
       <a href="#">Like</a> | 
       <a href="#">Dislike</a> | 
       <a href="#">Edit</a> | 
       <a href="{{ route('post.delete', [ 'post_id' => $post->id ]) }}">Delete</a> 
      </div> 
     </article> 
     @endforeach 

web.app маршруты

<?php 

use App\Task; 
use Illuminate\Http\Request; 

/* 
|-------------------------------------------------------------------------- 
| Web Routes 
|-------------------------------------------------------------------------- 
| 
| This file is where you may define all of the routes that are handled 
| by your application. Just tell Laravel the URIs it should respond 
| to using a Closure or controller method. Build something great! 
| 
*/ 

Route::group(['middleware' => ['web']], function() 
{ 
    Route::get('/', function() { 
     return view('welcome'); 
    })->name('home'); 

    // Route for signed up users 
    Route::post('/signup', [ 
     'uses' => '[email protected]', 
     'as' => 'signup' 
    ]); 

    // Redirect to signin 
    Route::post('/signin', [ 
     'uses' => '[email protected]', 
     'as' => 'signin' 
    ]); 

    //Redirect to the dashboard 
    Route::get('/dashboard', [ 
     'uses'  => '[email protected]', 
     'as'   => 'dashboard', 
     'middleware' => 'auth' 
    ]); 

    // Create a new post and route 
    Route::post('/createpost', [ 
     'uses' => '[email protected]', 
     'as' => 'post.create' 
    ]); 

    // Create a new post and route 
    Route::get('/delete-post/{post_id}', [ 
     'uses'  => '[email protected]', 
     'as'   => 'post.delete', 
     'middleware' => 'auth' 
    ]); 

}); 

И ошибка, которую я получаю

ErrorException in 3bda00b66abf627abd64dcb541751a9b753d4384.php line 33: 
Undefined variable: posts (View: C:\wamp\www\laravel\resources\views\dashboard.blade.php) 
    in 3bda00b66abf627abd64dcb541751a9b753d4384.php line 33 
at CompilerEngine->handleViewException(object(ErrorException), '1') in PhpEngine.php line 44 
at PhpEngine->evaluatePath('C:\wamp\www\laravel\storage\framework\views/3bda00b66abf627abd64dcb541751a9b753d4384.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag))) in CompilerEngine.php line 59 
at CompilerEngine->get('C:\wamp\www\laravel\resources\views/dashboard.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag))) in View.php line 150 
at View->getContents() in View.php line 121 
at View->renderContents() in View.php line 86 
at View->render() in Response.php line 45 
at Response->setContent(object(View)) in Response.php line 201 
at Response->__construct(object(View)) in Router.php line 1042 
at Router->prepareResponse(object(Request), object(View)) in Router.php line 642 
at Router->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 53 
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in SubstituteBindings.php line 41 
at SubstituteBindings->handle(object(Request), object(Closure)) in Pipeline.php line 137 
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in VerifyCsrfToken.php line 64 
at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php line 137 
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49 
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 137 
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 64 
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 137 
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37 
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 137 
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59 
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 137 
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104 
at Pipeline->then(object(Closure)) in Router.php line 644 
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 618 
at Router->dispatchToRoute(object(Request)) in Router.php line 596 
at Router->dispatch(object(Request)) in Kernel.php line 267 
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in Pipeline.php line 53 
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 46 
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 137 
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104 
at Pipeline->then(object(Closure)) in Kernel.php line 149 
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116 
at Kernel->handle(object(Request)) in index.php line 53 

Я не знаю, как передать $ сообщения переменных на просмотр файлов.

ответ

0

Если $posts имеет значение null, вы можете столкнуться с этой ошибкой. Вы можете попробовать инкапсулировать foreach с помощью

@if (isset($posts)) 
    @foreach ($posts as $post) 
    ... 
    @endforeach 
@endif 
+0

Это работает, и ошибка со страницы удалена, но не она не отображает никаких сообщений, которые пользователь имеет в базе данных. –

+0

Тогда, вероятно, ваш Post :: all() возвращает null. Вы можете проверить свою модель Post и базу данных. – berkayk

+0

Я нашел, что проблема UserController.php return view ('dashboard'); должно быть \t \t return redirect() -> route ('dashboard'); в противном случае он переходит к/signin маршруту. –

0

Вы сначала хотите проверить у контроллера, если $ post возвращает любые данные. Так сразу после этой строки;

$ posts = Post :: all();

Делают

дд ($ сообщений);

Если это возвращает любые записи, вы можете затем просмотреть свое мнение. Как упоминал ответ @ berkayk. Вы должны сделать несколько проверок на своем представлении, чтобы убедиться, что ваше представление не выдает ошибку или вообще возвращает другое представление, проверяя количество записей на контроллере.