Hello I have a problem with MaddHatter\LaravelFullcalendar\Calendar. I already try to look documentation and search in other question in stackoverflow but still didn't find the solution.
This is my eror :
Type error: Argument 1 passed to
MaddHatter\LaravelFullcalendar\Calendar::addEvent() must implement
interface MaddHatter\LaravelFullcalendar\Event, array given, called in
D:\XAMPP\htdocs\isei\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php
on line 221
EventController :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\EventModel;
use App\Branch;
use Calendar;
use MaddHatter\LaravelFullcalendar\Event;
class EventController extends Controller
{
public function getIndex()
{
$event = [];
$data = EventModel::all();
if($data->count())
{
foreach ($data as $key => $value)
{
$event[] = Calendar::event(
$value->title,
true,
new \DateTime($value->start_date),
new \DateTime($value->end_date.' +1 day')
);
}
}
$calendar = \Calendar::addEvent($event);
return view('event', compact('calendar'));
}
}
Event Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class EventModel extends Model implements \MaddHatter\LaravelFullcalendar\IdentifiableEvent
{
protected $table = 'event';
protected $fillable = [
'id_branch','title','start_date','end_date'
];
public function cabang()
{
return $this->hasOne('App\Branch', 'id', 'id_branch');
}
protected $dates = ['start', 'end'];
/**
* Get the event's id number
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Get the event's title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Is it an all day event?
*
* #return bool
*/
public function isAllDay()
{
return (bool)$this->all_day;
}
/**
* Get the start time
*
* #return DateTime
*/
public function getStart()
{
return $this->start;
}
/**
* Get the end time
*
* #return DateTime
*/
public function getEnd()
{
return $this->end;
}
}
try to change:
use MaddHatter\LaravelFullcalendar\Event;
at your EventController to this:
use MaddHatter\LaravelFullcalendar\Facades\Calendar;
add s to addEvent
$calendar = \Calendar::addEvents($event);
Related
I'm trying to write a unit test for the startedAt() method using mocks however the problem I'm facing is that I don't think I can access the builder instance from inside that startedAt() method.
To test the startedAt() method I created a fixture class called ExampleFilters and had it extend the parent class of Filters. Inside of the ExampleFilters class I import the FiltersByStartDate trait.
Does anyone have any suggestions on how I can access the builder property from the FiltersByStartDate trait?
Any ideas on this?
<?php
namespace App\Filters\Concerns;
trait FiltersByStartDate
{
/**
* Filter a query to include models of a specific date started.
*
* #param array $startedAt
* #return \Illuminate\Database\Eloquent\Builder
*/
public function startedAt($startedAt)
{
if (isset($startedAt[1])) {
$this->builder->whereHas('currentEmployment', function ($query) use ($startedAt) {
$query->whereBetween('started_at', [
$startedAt[0],
$startedAt[1]
]);
});
} else {
$this->builder->whereHas('currentEmployment', function ($query) use ($startedAt) {
$query->whereDate('started_at', $startedAt[0]);
});
}
return $this->builder;
}
}
<?php
namespace Tests\Fixtures;
use App\Filters\Concerns\FiltersByStartDate;
use App\Filters\Filters;
class ExampleFilters extends Filters
{
use FiltersByStartDate;
}
<?php
namespace App\Filters;
use Illuminate\Http\Request;
abstract class Filters
{
/**
* #var \Illuminate\Http\Request
*/
protected $request;
/**
* The Eloquent builder.
*
* #var \Illuminate\Database\Eloquent\Builder
*/
protected $builder;
/**
* Registered filters to operate upon
*
* #var array
*/
protected $filters = [];
/**
* Create a new class instance.
*
* #param \Illuminate\Http\Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Apply the filters.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
* #return \Illuminate\Database\Eloquent\Builder
*/
public function apply($builder)
{
$this->builder = $builder;
foreach ($this->getFilters() as $filter => $value) {
if (method_exists($this, $filter)) {
$this->$filter($value);
}
}
return $this->builder;
}
/**
* Fetch all relevant filters from the request.
*
* #return array
*/
public function getFilters()
{
return array_filter($this->request->only($this->filters));
}
}
<?php
namespace Tests\Unit\Filters\Concerns;
use Illuminate\Database\Query\Builder;
use Tests\Fixtures\ExampleFilters;
use Tests\TestCase;
/*
* #group filters
*/
class FiltersByStartDateTest extends TestCase
{
/* #var Tests\Fixtures\ExampleFilters */
protected $subject;
public function setUp(): void
{
$this->subject = app(ExampleFilters::class);
}
/** #test */
public function models_can_be_filtered_by_their_start_date()
{
// $this->markTestIncomplete();
$dateSet = ['2020-01-01 00:00:00'];
$mock = \Mockery::mock(Builder::class)
->shouldReceive('whereHas', \Mockery::any())
->shouldReceive('whereDate')
->withArgs(['started_at', $dateSet])
->once()
->andReturn(true)
->getMock();
dd($this->subject->startedAt($dateSet));
$builderMockFromDate = $this->subject->startedAt($dateSet);
$this->assertSame($builderMockFromDate, $mock);
}
}
I am unable to get my yajrabox-datatable to render in my view. I get the following error:
DataTables warning: table id=dataTableBuilder - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
I have set extended the datatables class and included return $dataTable->render('activities/index'); in my controller.
ActivitiesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Activity;
use DB;
use Yajra\Datatables\Datatables;
use Redirect,Response;
Use App\DataTables\ActivityDataTable;
use Session;
use Log;
class ActivitiesController extends Controller
{
public function index(ActivityDataTable $dataTable)
{
session(['source' => 'activities']);
Log::info('Visiting: index');
Log::info('Source: '.session('source'));
return $dataTable->render('activities/index');
}
}
ActivityDataTable.php
<?php
namespace App\DataTables;
use App\Activity;
use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\DataTables;
class ActivityDataTable extends DataTable
{
/**
* Display ajax response.
*
* #return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->make(true);
}
/**
* Build DataTable class.
*
* #param mixed $query Results from query() method.
* #return \Yajra\DataTables\DataTableAbstract
*/
public function dataTable($query, DataTables $dataTables)
{
return $dataTables->eloquent($query);
}
/**
* Get query source of dataTable.
*
* #param \App\Activity $model
* #return \Illuminate\Database\Eloquent\Builder
*/
public function query()
{
// $query=Activity::all()->take(50);
// return Datatables::of($query)
// ->addColumn('user', function ($query) {
// return $query->user->name;
// })->make(true);
return Activity::query();
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->parameters($this->getBuilderParameters());
}
/**
* Get parameters.
*
* #return array
*/
protected function getBuilderParameters()
{
return [
'dom' => 'Bfrtip',
'buttons' => ['excel'],
];
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
'id',
'month',
'activity',
'learned',
'role',
'hours',
'user',
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
return 'Activity_' . date('YmdHis');
}
}
Okay,
I was using a guide that was for an older version of yajra-datatables.
Following this upgrade guide resolved my issue:
https://yajrabox.com/docs/laravel-datatables/7.0/upgrade
I have a custom repository in my Symfony's project and I want use like a search tool. My project' structure is the following:
P.D. UPDATED Question and code
-Manager:
* BaseManager.php
* MyEntityManager.php
-Repository:
* BaseRepository.php
* MyEntityRepository.php
Well, I want access to my custom repository and use the following method findByTitle, which method should return an array with objects which description field be similar. I put a simple print (var_dump of the term entered) inside of my function to see if my browser shows it, but it isn't showed yet...
My BaseManager:
<?php
namespace AppBundle\Manager;
use AppBundle\Repository\BaseRepository;
class BaseManager
{
/**
* #var BaseRepository
*/
protected $repo;
/**
* #param BaseRepository $repo
*/
public function __construct(BaseRepository $repo)
{
$this->repo = $repo;
}
/**
* #param $model
* #return bool
*/
public function create($model)
{
return $this->repo->create($model);
}
/**
* #param CrudModel $model
* #return bool
*/
public function update($model)
{
return $this->repo->save($model);
}
/**
* #param CrudModel $model
* #return bool
*/
public function delete($model)
{
return $this->repo->delete($model);
}
/**
* #param $id
* #return null|object
*/
public function getOneById($id)
{
return $this->repo->findOneById($id);
}
/**
* #return array
*/
public function all()
{
return $this->repo->all();
}
}
MyEntityManager:
<?php
namespace AppBundle\Manager;
use AppBundle\Repository\MyEntityRepository;
use AppBundle\Entity\MyEntity;
/**
* Class MyEntityManager
* #package AppBundle\Manager
*/
class MyEntityManager extends BaseManager{
public function findByTitle($title){
echo '<h1>flux of code here</h1>';
return $this->repo->findByTitle($title);
}
public function findSimilars($term){
echo '<h1>flux of code here</h1>';
return $this->repo->findSimilars($term);
}
}
BaseRepository:
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
abstract class BaseRepository extends EntityRepository
{
public function create($model, $autoFlush = true)
{
return $this->insert($model,$autoFlush);
}
public function save($model, $autoFlush = true)
{
return $this->insert($model,$autoFlush);
}
public function delete($model)
{
try{
$this->getEntityManager()->remove($model);
$this->getEntityManager()->flush();
return true;
}catch (\Exception $e){
echo $e->getMessage();
}
}
public function findOneById($id)
{
return $this->findOneBy(array('id' => $id));
}
public function all()
{
return $this->findAll();
}
private function insert($model, $autoFlush = true)
{
$this->getEntityManager()->persist($model);
if ($autoFlush) {
$this->getEntityManager()->flush();
return true;
}
}
}
MyEntityRepository:
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* Class MyEntityRepository
* #package AppBundle\Repository
*/
class MyEntityRepository extends BaseRepository{
private function findById($id){
$query = $this->createQueryBuilder('myentity')
->where('myentity.id = :id')
->setParameter('id', $id)
->getQuery();
$myentity = $query->getResult();
return $myentity;
}
private function findByTitle($term){
echo '<h1>';
var_dump($term);
echo '</h1>',
$query = $this->createQueryBuilder('myentity')
->andwhere('myentity.description = :description')
->setParameter('description', $term)
->getQuery();
$myentity = $query->getResult();
return $myentity;
}
}
The beginning of MyEntity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* #ORM\Table(name="myentity")
* #ORM\Entity
* #ORM\Entity(repositoryClass="AppBundle\Repository\MyEntityRepository")
*/
class MyEntity {
......
My services.yml:
parameters:
app.myentity.repository.class: AppBundle\Repository\MyEntityRepository
app.myentity.manager.class: AppBundle\Manager\MyEntityManager
services:
app.myentity.repository:
class: %app.myentity.repository.class%
public: true
factory_service: doctrine.orm.entity_manager
factory_method: getRepository
arguments: [ AppBundle\Entity\MyEntity ]
app.myentity.manager:
class: %app.myentity.manager.class%
arguments: [#app.myentity.repository]
And I'm calling my service in the following way:
public function searchAction(Request $request, $term){
$manager = $this->get('app.myentity.manager');
$result = $manager->findByTitle($term);
echo '<h5>';
var_dump($result);
echo '</h5>';
....
}
Just a guess, as your question is far from being clear (esp. the last paragraph): did you only register the service, or did you also tell Symfony to use the repository for the entity (presumably MyEntity)? For instance, using annotations, you’d need something like this:
#ORM\Entity(repositoryClass="The\RepositoryClass")
The problem was that I declared my function as private instead of public
private function findByTitle($term){
instead of
public function findByTitle($term){
Right now I try this query with eloquent:
'MentorId' => $employee->intern(true)->mentor(true)->MentorId,
And in my employee and intern model I've got this:
Intern
/**
* #return mixed
*/
public function intern($withTrashed = false)
{
if($withTrashed == true)
{
return $this->belongsTo(internModel::class, 'InternId')->withTrashed();
}
return $this->belongsTo(internModel::class,'InternId');
}
Mentor
/**
* #return mixed
*/
public function mentor($withTrashed = false)
{
if($withTrashed == true)
{
return $this->belongsTo(mentorModel::class, 'MentorId')->withTrashed();
}
return $this->belongsTo(mentorModel::class,'MentorId');
}
But it crashes:
BadMethodCallException in Builder.php line 2148:
Call to undefined method Illuminate\Database\Query\Builder::mentor()
How could I fix this?
--EDIT--
Employee
<?php
namespace App\src\employee;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\src\department\Department as departmentModel;
use App\src\employee\Employee as employeeModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\src\intern\Intern as internModel;
use App\src\mentor\Mentor as mentorModel;
use App\src\employee\Role as roleModel;
class Employee extends Authenticatable
{
use SoftDeletes;
use EmployeeServiceTrait;
/**
* table name
*/
protected $table = 'employee';
/**
* Mass assignment fields
*/
protected $fillable = ['RoleId', 'DepartmentId', 'InternId', 'FirstName', 'LastName', 'Bio','api_token', 'email', 'LinkedIn', 'password', 'Address', 'Zip', 'City', 'ProfilePicture', 'BirthDate', 'StartDate', 'EndDate', 'Suspended','LinkedIn'];
/**
* Primarykey
*/
protected $primaryKey = 'EmployeeId';
/**
* Deleted_at
*/
protected $dates = ['deleted_at'];
/**
* #return mixed
*/
public function role()
{
return $this->belongsTo(roleModel::class,'RoleId');
}
/**
* #return mixed
*/
public function intern($withTrashed = false)
{
if($withTrashed == true)
{
return $this->belongsTo(internModel::class, 'InternId')->withTrashed();
}
return $this->belongsTo(internModel::class,'InternId');
}
/**
* #return mixed
*/
public function department()
{
return $this->belongsTo(departmentModel::class,'DepartmentId');
}
/**
* #return mixed
*/
public function mentor()
{
return $this->belongsTo(mentorModel::class,'MentorId');
}
/**
* #return mixed
*/
public function employees()
{
return $this->hasManyThrough(employeeModel::class,departmentModel::class,'CompanyId','DepartmentId');
}
/**
* #param $role
* #return bool
*/
public function hasRole($role)
{
if(strtolower($this->role->RoleName) == strtolower($role))
{
return true;
}
return false;
}
}
The problem you have is that any Eloquent relationship object is actually an instance of Relation. This means when you create relationships you actually return a collection (instance of Builder); Hense your error:
BadMethodCallException in Builder.php line 2148:
Call to undefined method Illuminate\Database\Query\Builder::mentor()
The simple solution, without any modification to your code would be something like:
'MentorId' => $employee->intern(true)->first()->mentor(true)->first()->MentorId;
However, you could use overloading like the following:
'MentorId' => $employee->intern->mentor->MentorId;
Although this will NOT include your withTrashed. You can however tweak your relationship to something like:
public function intern($withTrashed = false)
{
$relation = $this->belongsTo(internModel::class, 'InternId');
if($withTrashed == true)
{
return $relation->withTrashed()->first();
}
return $relation->first();
}
But I wouldn't advise this because later on if you try using things like WhereHas you will get errors. That said, another way would be to do something along the following lines:
public function intern()
{
return $this->belongsTo(internModel::class, 'InternId');
}
Then get trashed like:
'MentorId' => $employee->intern()->withTrashed()->first()->mentor()->withTrashed()->first()->MentorId;
Try as below as per laravel guide. Keep in mind that parent model must have hasOne/hasMany method and child model must have belongsTo method.
Intern
/**
* #return mixed
*/
public function intern($withTrashed = false)
{
if($withTrashed == true)
{
return $this->hasOne('App\Intern', 'InternId')->withTrashed();
}
return $this->hasOne('App\Intern','InternId');
}
Employee
/**
* #return mixed
*/
public function intern($withTrashed = false)
{
if($withTrashed == true)
{
return $this->belongsTo('App\Intern', 'InternId')->withTrashed();
}
return $this->belongsTo('App\Intern','InternId');
}
Note: Same for all other models.
I'm having some troubles getting a piece of code to work in laravel. I have a SecuredEloquent class that all my 'secured' models extend. what it does is simply add a whereHas clause to the query in the newQuery function I override:
class SecuredEloquent extends Eloquent
{
public function newQuery($excludeDeleted = true)
{
$query = parent::newQuery($excludeDeleted);
$context = App::make('Wall\Context\Context');
$query->whereHas('permissions', function($q) use ($context)
{
$q->where('context_id','=',$context->id());
$q->where('level','>=', $context->level());
});
return $query;
}
}
The problem: it doesn't work. I get "The connection was reset" errors in my browser and nothing in the log :( anyone any idea what I'm doing wrong?
edit2:
MyModel extends SecuredEloquent, OtherModel doesn't
When I try to run it in artisan tinker nothing happens.
var_dump(MyModel::all()); simply stops the process (it crashes? no idea, again nothing logged, it simply quits)
var_dump(OtherModel::all()); however simply works
edit:
I have ContextServiceProvider:
use Illuminate\Support\ServiceProvider;
class ContextServiceProvider extends ServiceProvider
{
/**
* Register
*/
public function register()
{
$this->app->singleton('Wall\Context\Context', function($app)
{
return new AppContext;
});
}
}
with AppContext:
use Illuminate\Database\Eloquent\Model;
class AppContext
{
/**
* The current context
*
* #var Illuminate\Database\Eloquent\Model
*/
protected $context;
/**
* The current context level
*
* #var int
*/
protected $level;
/**
* Check to see if the context has been set
*
* #return boolean
*/
public function has()
{
if($this->context) return true;
return false;
}
/**
* Get the context identifier
*
* #return integer
*/
public function id()
{
if ( $this->has() ) return $this->context->id;
return 0;
}
/**
* Get the context permission leven
*
* #return string
*/
public function level()
{
if ( $this->level ) return $this->level;
return 1;
}
}
Hope this helps