Laravel 5.8 | FullCalendar display events on calendar - php

I am trying to display events on calendar from this package:
composer require maddhatter/laravel-fullcalendar
I did model:
class Event extends Model
{
protected $fillable = [
'title',
'start_date',
'end_date',
];
}
Event migrations with same columns. In controller I have function:
public function all()
{
$events = [];
$data = Event::all();
if($data->count()) {
foreach ($data as $key => $value) {
$events[] = Calendar::event(
$value->title,
true,
new \DateTime($value->start_date),
new \DateTime($value->end_date.' +1 day'),
null,
[
'color' => '#f05050',
]
);
}
}
$calendar = Calendar::addEvents($events);
return view('pages.block.event.all', compact('calendar'));
}
and in my all.blade.php:
{!! $calendar->calendar() !!}
the calendar is displayed correctly, but no events are applied to it. Could someone help me? Thank you

Related

How to add object in laravel relationships

How to add extra object in laravel relationship when fatch data.
Here is my code:
$list = new self;
$list = $list->where('uuid', $uuid);
$list = $list->where('user_id', $user->id)->orWhere('to_user_id', $user->id);
$list = $list->with(['touser' => function($q1) {
$q1 = $q1->select('id', 'name', 'email', 'user_image', 'is_active', 'is_profile_completed', 'is_verified');
}]);
$list->with(['user' => function($q1) {
$q1 = $q1->select('id', 'name', 'email', 'user_image', 'is_active', 'is_profile_completed', 'is_verified');
}]);
$list = $list->first();
I want to add extra object in response like:
"Contest": {
"name": NULL,
"type": 0
}
You have multiple ways to add extra objects in response
The first option is
You have to define the eloquent relationship in the list model like this
public function contest()
{
return $this->belongsTo(Contest::class);
}
and then you can eager load that relationship using a method like this
$list->with('contest')->first();
another option is
You can set custom relationships like this
$list->setRelation('contest', collect(['name'=>null,'type':0]));
try this:
$list->prepend([
'Contest' => [
'name' => null,
'type' => 0
]
]);

Laravel comment rating

I have simple comment rating logic now.
For example i have following controller :
public function rating_change(Request $request, Comment $comment)
{
if ($request['action'] == 'up') {
$comment->positive_rating = $comment->positive_rating + 1;
} else if ($request['action'] == 'down') {
$comment->negative_rating = $comment->negative_rating + 1;
}
$comment->save();
return ['positive' => $comment->positive_rating, 'negative' => $comment->negative_rating];
}
And the route for that method:
Route::put('/comments_rating/{comment}', function (Comment $comment, Request $request) {
$commentController = new CommentController();
return $commentController->rating_change($request, $comment);
});
Model:
class Comment extends Model
{
use HasFactory;
protected $fillable = [
'body',
'user_id',
'item_id'
];
protected $casts = [
'user_id' => 'integer',
'item_id' => 'integer',
];
public function author()
{
return $this->belongsTo(User::class, 'user_id');
}
public function post()
{
return $this->belongsTo(Items::class, 'id');
}
}
And resource:
return [
'id' => $this->id,
'user_id'=>$this->user_id,
'body'=>$this->body,
//https://github.com/jenssegers/date
'created_at' => Date::parse($this->created_at)->diffForHumans(),
'updated_at' => $this->updated_at->format('Y-m-d H:i'),
'author'=>[
'id'=>$this->author->id,
'name'=>$this->author->name,
],
'rating'=>[
'positive'=>$this->positive_rating,
'negative'=>$this->negative_rating
]
];
The current purpose to prevent change rating by the same user multiple times.(Server side block)
And return the following flag (changed or smth) to frontend.
How should i to do this?
Should i use the separate table and store all user actions to get flag of changed them in all my comments?
Should i use the https://laravel.com/docs/8.x/redis for that purpose or sql is enough?
Maybe there is some built in laravel solutions or libraries?
I use laravel sanctum to authorize.

Using polymorphic relation how to save array data?

I want to save array of data using polymorphic relation one to many.
I have the following Models.
schedule task model
class ScheduleTask extends Model
{
protected $guarded = [];
public function taskable()
{
return $this->morph To(__FUNCTION__, 'taskable_type', 'taskable_id');
}
}
prelimstest model
class PrelimsTest extends Model
{
public function tasks()
{
return $this->morph Many(Schedule Task::class, 'taskable');
}
}
maintest model
class MainsTest extends Model
{
public function tasks()
{
return $this->morphMany(ScheduleTask::class, 'taskable');
}
}
video model
class Video extends Model
{
public function tasks()
{
return $this->morphMany(ScheduleTask::class, 'taskable');
}
}
And my controller
class ScheduleController extends Controller
{
public function store(Request $request)
{
$data = array();
foreach ($prelims_id as $key => $value) {
$data[] = [
'course_id' => $prelims_course_id[$key],
'status' => 'incomplete',
'schedule_id' => 1
];
$prelims_save = PrelimsTest::find($value);
}
$prelims_save->tasks()->createMany($data);
$data2 = array();
foreach ($mains_id as $key2 => $value2) {
$data2[] = [
'course_id' => $mains_course_id[$key2],
'status' => 'incomplete',
'schedule_id' => 1
];
$mains_save = MainsTest::find($value2);
}
$mains_save->tasks()->createMany($data2);
$data3 = array();
foreach ($videos_id as $key3 => $value3) {
$data3[] = [
'course_id' => $videos_course_id[$key3],
'status' => 'incomplete',
'schedule_id' => 1
];
$videos_save = Video::find($value3);
}
$videos_save->tasks()->createMany($data3);
}
}
My problem is while i'm saving taskable_id enters last value of array.
Does anyone know how to solve this part, that I can save the polymorphic relation?
Thanks in advance.

Laravel Nova, custom options belongsTo

How I can add custom options in a belongsTo, I found another solution, but I think isn't correct/beauty
public function fields(Request $request)
{
$rooms = array();
$resourceId = ($request->viaResourceId) ? $request->viaResourceId : $request->resourceId;
$event = \App\Event::where('id', $resourceId)->first();
$rooms = array();
foreach ($event->hotels()->get() as $hotel) {
foreach ($hotel->roomTypes()->get() as $room) {
$rooms[$room->id] = $hotel->name.' - '.$room->title;
}
}
return [
(new Tabs('Configuración', [
'Tarifa' => [
BelongsTo::make('Evento', 'event', Event::class)->required(),
Select::make('Habitación', 'room_type_id')->options($rooms)->displayUsingLabels(),
BelongsTo::make('Régimen', 'board', Board::class)->required(),
Money::make('Importe', 'EUR', 'amount')->required(),
],
'Fechas' => [
Date::make('Fecha desde', 'checkin')->required()->creationRules(REQUIRED, 'after_or_equal:today'),
Date::make('Fecha desde', 'checkout')->required()->rules(REQUIRED, 'after_or_equal:checkin'),
],
'Cupo' => [
Number::make('Ocupación', 'quota')->required()->hideFromIndex(),
Number::make('Reservados', 'booked')->readonly()->hideFromIndex(),
],
'Info Adicional' => $this->detailDataPanel(),
]))->withToolbar()
];
}
I want
Select::make('Habitación', 'room_type_id')->options($rooms)->displayUsingLabels(),
convert to
BelongsTo::make('Habitación', 'room_type_id')->options($rooms)->displayUsingLabels(),
I tried with relatables, but Room Types depend of the Hotels related with Event.

Laravel Validation With Multi Select

I'm making a multi select form element for updating schools and specialties pivot table school_specialty. The problem is that when I change only something in multi select not other inputs or textareas, I can't listen model events so I can't sync school_specialty table. But when I fill in any other input it's works perfect. Here's my multi select from blade:
{{Form::select('specialties[]', $specialties_data, $school->specialties, array('multiple' => 'true', 'id' => 'multi-select'))}}
This is my update method from school controller:
public function update($id)
{
$data = Input::only('name', 'type_id', 'description', 'info_specialties', 'contacts', 'specialties', 'financing_id', 'district_id', 'city_id');
$school = School::find($id);
$school->name = $data['name'];
$school->type_id = $data['type_id'];
$school->description = $data['description'];
$school->info_specialties = $data['info_specialties'];
$school->contacts = $data['contacts'];
$school->cover_photo = Input::file('cover_photo');
$school->set_specialties = $data['specialties'];
$school->financing_id = $data['financing_id'];
$school->set_district_id = $data['district_id'];
$school->city_id = $data['city_id'];
try {
$school->save();
} catch (ValidationException $errors) {
return Redirect::route('admin.schools.edit', array($id))
->withErrors($errors->getErrors())
->withInput();
}
return Redirect::route('admin.schools.edit', array($id))
->withErrors(array('mainSuccess' => 'School was created.'));
}
And here's my example school model:
<?php
class School extends Eloquent {
protected $table = 'schools';
protected $fillable = array('name', 'type_id', 'description', 'city');
protected $guarded = array('id');
protected $appends = array('specialties');
public $set_specialties;
public $set_district_id;
protected static function boot()
{
parent::boot();
static::updating(function($model)
{
$data = array(
'name' => $model->name,
'type_id' => $model->type_id,
'description' => $model->description,
'specialties' => $model->set_specialties,
'city_id' => $model->city_id
);
$rules = array(
'name' => 'required|min:3|max:50',
'type_id' => 'required|min:1|max:300000',
'description' => 'required|min:10',
'specialties' => 'required|array',
'city_id' => 'required|min:1|max:300000'
);
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
throw new ValidationException(null, null, null, $validator->messages());
} else {
return true;
}
});
static::updated(function($model)
{
if ( $model->set_specialties != null )
{
$model->specialty()->sync($model->set_specialties);
}
});
}
public function specialty()
{
return $this->belongsToMany('Specialty', 'school_specialty');
}
}
?>
When updating only school specialities the School model events aren't triggered because the School model stays the same.
I think the simplest and most elegant solution is to touch the school model instance. This will modify the updated_at field for the School object and thus trigger the model events.
To do this add the following lines before the try/catch block:
if ($school->set_specialties !== null) {
$school->touch();
}
Also, validation shouldn't be handled in the model observers. Check form request validation here: https://laravel.com/docs/5.6/validation#form-request-validation.

Categories