Eager loading in Laravel 9 vs 5 - laravel

I am upgrading a project from Laravel 5 to Laravel 9, and one of the Controller methods seems to break and I cant figure out why. It works perfectly fine in Laravel 5, I get all the models returned. It fails when trying to load the 'liveConfig' and 'draftConfig' models.
Error
PHP Error: Call to a member function addEagerConstraints() on null in /var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php
Controller
public function show($siteId)
{
return auth()->user()->editing()->findOrFail($siteId)->augmented();
}
Relationships
public function liveConfig()
{
if (!$this->theme) {
return;
}
return $this->hasOne(LiveConfig::class)->where('status',
'live');
}
public function draftConfig()
{
if (!$this->theme) {
return;
}
return $this->hasOne(LiveConfig::class)->where('status',
'draft');
}
Eager Loading method
public function augmented()
{
$this->load([
'theme',
'theme.renewalPlans',
'subscription',
'subscription.nextSubscription',
'liveConfig',
'draftConfig',
])->append('open_invoices_count', 'cmsStyling', 'cmsStylesheets');
}

Related

Laravel OBSERVER update process

In SESSObServer
public function updated(SESS $sESS)
{
log::info("data updated");
if ($sESS->wasChanged('is_active')) {
log::info("data updated");
}
}
IN Observer, created(SESS $sESS) function run but update is not run. How can i solve problem ?
I changed my query. Now, this is run.
I didn't use get. I used first()
$sess = SESS::where('sess_id', request('id'))->first();
$sess->save();
Make sure your Observer is registered.
# app/Providers/EventServiceProvider.php
use App\Models\SESS;
use App\Observers\SESSObserver;
class EventServiceProvider extends ServiceProvider
{
public function boot()
{
SESS::observe(SESSObServer::class);
}
}
Make sure you're using the correct classes. The logger's class is Log (capital L)
public function updated(SESS $sESS)
{
Log::info("data updated");
if ($sESS->wasChanged('is_active')) {
Log::info("data updated");
}
}
Alternatively, I think you can still use info().
public function updated(SESS $sESS)
{
info("data updated");
if ($sESS->wasChanged('is_active')) {
info("data updated");
}
}
If you're using apache, make sure the apache user can write to the log file.

Is it possible to retrieve a value from a redirect in another class before performing the redirect?

I am currently working with a controller, OnboardingController.php. This controller calls another method in a different class, let's call it OnboardingService.php, so for example:
OnboardingController
public function doThing()
{
return $this->doAnotherThing();
}
OnboardingService
public function doAnotherThing()
{
return redirect('/')->with(['propertyA' => 'valueA']);
}
Would I be able to access propertyA in OnboardingController before returning the redirect? And if so, how would I access that property?
e.g.
OnboardingController
public function doThing()
{
$doAnotherThing = $this->doAnotherThing();
Log::info($doAnotherThing->propertyA);
return $doAnotherThing;
}
I am currently using Laravel 6.
You're using redirect(...)->with(...) to flash propertyA, so propertyA should be accessible from the session
public function doThing()
{
$doAnotherThing = $this->doAnotherThing();
Log::info(session()->get('propertyA'));
return $doAnotherThing;
}

easyaDmin 3.3 create custom filter

I struggle to understand how i'm supposed to do a custom filter in easyadmin 3.3 . The documentation isnt helping. I alway got an error
Error: Class App\Entity\entity1 has no field or association named "field1"
So i tried to put the mapping as false to prevent this, following the doc and i'm getting this
Attempted to call an undefined method named "mapped" of class "App\Controller\Admin\Filter\customfilter".
here my code :
Crud controller :
public function configureFilters(Filters $filters): Filters
{
return $filters
->add(getAutoclaveFilter::new('fiedWithNoAssociation')->mapped(false))
;
}
custom filter :
class GetAutoclaveFilter implements FilterInterface
{
use FilterTrait;
public static function new(string $propertyName, $label = null): self
{
return (new self())
->setFilterFqcn(__CLASS__)
->setProperty($propertyName)
->setLabel($label);
}
public function apply(QueryBuilder $queryBuilder, FilterDataDto $filterDataDto, ?FieldDto $fieldDto, EntityDto $entityDto): void
{
$queryBuilder->andWhere(sprintf('%s.%s = :value', $filterDataDto->getEntityAlias(), $filterDataDto->getProperty()))
->setParameter('value',$filterDataDto );
}
And the entity :
public function fiedWithNoAssociation()
{
return $this->getEntityAssociated()->getEntity2();
}
What i'm doing wrong ? Is the mapped function not implemented yet ?
Use instead of mapped:
->setFormTypeOption('mapped', false)

one controller for three pages

I have one controller ADD. I want this controller to manipulate three pages: add_customer page, add_project page and add_post_page.In this case add_project page works perfectly. But add_customer and add_post pages have errors:
Failed to load resource: the server responded with a status of 500 (Internal Server Error).
I think the problem is in my coditions here:
public function index(){
if($this->uri->segment(3)=='add_customer'){
$this->add_customer();
}
else if($this->uri->segment(3)=='add_post'){
$this->add_post();
}
else{
$this->add_project();
}
}
This is my full controller:
class ADD extends MX_Controller {
public $mname, $tag, $tpl;
function __construct()
{
$this->mname=strtolower(get_class());
$this->tag=strtoupper($this->mname);
}
public function index(){
if($this->uri->segment(3)=='add_customer'){
$this->add_customer();
}
else if($this->uri->segment(3)=='add_post'){
$this->add_post();
}
else{
$this->add_project();
}
}
public function add_project()
{
include APPPATH."language/".LANG.".php";
$this->load->model($this->mname.'/add_project_model');
$model='add_project_model';
$this->$model->index($this->mname);
$a['IsEnabled']=$LANGUAGE['IsEnabled'];
$a['Submit']=$LANGUAGE['Submit'];
$a['Cancel']=$LANGUAGE['Cancel'];
$a['Reset']=$LANGUAGE['Reset'];
$a['Name']=$LANGUAGE['Name'];
$a['SelectCustomer']=$LANGUAGE['SelectCustomer'];
$a['Project Name']=$LANGUAGE['ProjectName'];
$a['Manager']=$LANGUAGE['Manager'];
$a['Customer']=$LANGUAGE['Customer'];
$userGROUP = $this->session->userdata('_userGROUP');
if ($userGROUP=='Administrator')
$a['AddManager']='<button type="button" class="btn btn-warning" onclick="AddNewManager()">+</button>';
else
$a['AddManager']='';
$this->tp->assign($a);
$this->tp->parse('CONTENT', $this->mname.'/add_project.tpl');
}
public function add_customer()
{
include APPPATH."language/".LANG.".php";
$userGROUP = $this->session->userdata('_userGROUP');
if($userGROUP!=='Administrator')
{
show_404('page');
exit;
}
$this->load->model($this->mname.'/add_customer_model');
$model='add_customer_model';
$this->$model->index($this->mname);
$a['IsEnabled']=$LANGUAGE['IsEnabled'];
$a['Submit']=$LANGUAGE['Submit'];
$a['Cancel']=$LANGUAGE['Cancel'];
$a['Reset']=$LANGUAGE['Reset'];
$a['Name']=$LANGUAGE['Name'];
$a['Project Name']=$LANGUAGE['CustomerName'];
$a['Customer Name']=$LANGUAGE['Customer Name'];
$this->tp->assign($a);
$this->tp->parse('CONTENT', $this->mname.'/add_customer.tpl');
}
public function add_post()
{
include APPPATH."language/".LANG.".php";
$userGROUP = $this->session->userdata('_userGROUP');
if($userGROUP=='Engineer')
{
show_404('page');
exit;
}
$this->load->model($this->mname.'/add_post_model');
$model='add_post_model';
$this->$model->index($this->mname);
$a['IsEnabled']=$LANGUAGE['IsEnabled'];
$a['Submit']=$LANGUAGE['Submit'];
$a['Cancel']=$LANGUAGE['Cancel'];
$a['Reset']=$LANGUAGE['Reset'];
$a['Activity Name']=$LANGUAGE['Activity Name'];
$a['SalaryHour']=$LANGUAGE['SalaryHour'];
$this->tp->assign($a);
$this->tp->parse('CONTENT', $this->mname.'/add_post.tpl');
}
}
How can I resolve this problem?
Just Give it a Try, Hope it works :
public function index(){
if($this->uri->segment(3)=='add_customer'){
redirect(base_url().'/Add/add_customer');
//$this->add_customer();
}
else if($this->uri->segment(3)=='add_post'){
redirect(base_url().'/Add/add_post');
//$this->add_post();
}
else{
redirect(base_url().'/Add/add_project');
//$this->add_project();
}
}
Your index function is never reached
This would reach it : http://project.dev/add
By default the following urls hit the appropriate function.
http://project.dev/add/add_customer hit public function add_customer()
http://project.dev/add/add_post hit public function add_post()
If you are getting errors check out the various error in the specific function and make sure you have error reporting turned on

Testing Laravel Event Listener

I'm trying to test Event Listener in Laravel.
This is my listener:
class FlashNotifier
{
public function handleMenuItemWasStored()
{
Session::flash('flash-status', 'success');
Session::flash('flash-message', 'Item was stored.');
}
public function subscribe($events)
{
$events->listen(
MenuItemWasStored::class,
'\App\Listeners\Menu\FlashNotifier#handleMenuItemWasStored'
);
}
}
And this is the test I came up so far:
public function testEventListenerWasTriggered()
{
$listener = Mockery::mock('App\Listeners\Menu\FlashNotifier');
$d = new Dispatcher;
$listener->shouldReceive('handleMenuItemWasStored')->once();
$d->fire('App\Events\Menu\MenuItemWasStored');
}
However, I get the following exception:
1) FlashListenerTest::testEventListenerWasTriggered
Mockery\Exception\InvalidCountException: Method handleMenuItemWasStored() from Mockery_1_App_Listeners_Menu_FlashNotifier should be called
exactly 1 times but called 0 times.
What am I doing wrong?

Resources