Laravel在对象存在时返回错误

I have an global __construct() function inside my basecontroller, what looks like this:

public function __construct() { 
    $alerts = Alert::orderBy('id', 'DESC')->whereNull('deleted_at')->get();
    return View::share('alert', $alerts);
}

This works on every page except on 2 pages...

My route looks like this:

Route::resource('/', 'WebsiteController');

Route::get('nieuws/{id}', 'NewsController@show');

Route::resource('login', 'LoginController');

Route::resource('auth', 'LoginController@auth');

Route::resource('logout', 'LoginController@logout');

Route::resource('foto', 'PictureController');

Route::resource('studio', 'PictureController@showStudioPics');

//special routing for the mirrors
Route::get('spiegels', 'PictureController@getPicList');

Route::get('spiegels/{dirName}', 'PictureController@showPicList');
//end of special routing

Route::resource('calendar', 'CalendarController');

Route::get('history', function()
{
    return View::make('home.history');
});

Route::get('publicity', function()
{
    return View::make('home.publicity');
});

The pages that aren't working are the following:

  • publicity
  • history

The error I get is Undefined variable: alert but that's weird, because inside my view I have this:

@foreach($alert as $alert)
<div class="alert alert-{{ $alert->type }}" role="alert" style="margin-bottom:-10px;">{{ $alert->message }}</div>
@endforeach

And on all the other pages it does work.

What do I wrong?

The two views that aren't working are not using any controller and thus are not extending the BaseController. If you create a controller for them which extends the Base one instead of having the function inside the route file then your issue is resolved.

Do this as follows:

1) Create a controller "ContentControler.php" which extends BaseController exactly like your other controllers do already.

Then have two methods:

public function getHistory()
{ 
return view('home.history');
}

public function getPublicity()
{ 
return view('home.publicity');
}

and in your routes:

change this:

Route::get('history', function()
{
    return View::make('home.history');
});

Route::get('publicity', function()
{
    return View::make('home.publicity');
});

to this

Route::get('history', 'App\Http\Controllers\ContentController@getHistory')
Route::get('publicity', 'App\Http\Controllers\ContentController@getPublicity')

*** In Laravel 4 Controllers do not fall under the App\Http\Controllers namespace so in routes you only need to declare the controllerName@methodName without the namespace which is a new feature of Laravel 5.