我在我的网站laravel 5.6中使用fullcalendar并且它工作:)但是当我改变视图时我有这个问题:
Undefined variable: calendar_details
在我的视图layout.app中,我有这个:
{!! $calendar_details->script() !!}
我可以在所有控制器和视图中定义此var以避免所有问题吗?
这是我的EventsController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Http\Controllers\Controller;
use Auth;
use Validator;
use App\Events;
use Calendar;
class EventsController extends Controller
{
public function index(){
$events = Events::get();
$event_list = [];
foreach ($events as $key => $event){
$event_list[] = Calendar::event(
$event->event_name,
true,
new \DateTime($event->start_date),
new \DateTime($event->end_date)
);
}
$calendar_details = Calendar::addEvents($event_list);
return view('events', compact('calendar_details'));
}
public function addEvent(Request $request){
$validator = Validator::make($request->all(), [
'event_name' => 'required',
'start_date' => 'required',
'end_date' => 'required',
]);
if ($validator->fails()){
\Session::flash('warning', 'Veuillez entrer des informations valide');
return Redirect::to('/events')->withInput()->withErrors('warning');
}
$event = new Events;
$event->event_name = $request['event_name'];
$event->start_date = $request['start_date'];
$event->end_date = $request['end_date'];
$event->save();
\Session::flash('success', 'Evènement ajouté avec succès');
return Redirect::to('/events');
}
}
这是我的Events.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Events extends Model
{
protected $fillable = [
'event_name', 'start_date', 'end_date'
];
}
答案 0 :(得分:1)
打开 app / Providers / AppServiceProvider ,然后在 boot()方法中添加:
use Illuminate\Support\Facades\View;
use App\Events;
use Calendar;
...
View::composer('layout', function ($view) {
$events = Events::get();
$event_list = [];
foreach ($events as $key => $event){
$event_list[] = Calendar::event(
$event->event_name,
true,
new \DateTime($event->start_date),
new \DateTime($event->end_date)
);
}
$view->with('calendar_details', Calendar::addEvents($event_list));
});
请注意,类导入应位于文件的顶部。这段代码的作用是每次编译 layout 视图时,都会添加calendar_details。