Passing outer function parameter to inner function Laravel - laravel-8

I have the code bellow aimed at retrieving all the service providers using the service ID
public function getProvidersByPackage($id = null){
$package_id = $id;
$providers = ServiceProvider::whereHas('services', function($query) {
$query->where('packages.id', 1);
})->get();
dd($providers);
}
I would like to replace the constant 1 with the variable $id passed to the outer function getProvidersByPackage()
my problem is that when I try the following
public function getProvidersByPackage($id = null){
$package_id = $id;
$providers = ServiceProvider::whereHas('services', function($query) {
$query->where('packages.id', $id);
})->get();
dd($providers);
}
I get the error $id is not defined and when I try
public function getProvidersByPackage($id = null){
$package_id = $id;
$providers = ServiceProvider::whereHas('services', function(&$package_id, $query) {
$query->where('package.package_id', $package_id);
})->get();
}
I get the ArgumentCountError bellow
Too few arguments to function
App\Http\Controllers\ShopController::App\Http\Controllers\{closure}(), 1 passed in
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 1207
and exactly 2 expected
What could I be doing wrong?

In PHP, you can pass a variable to a closure using the use syntax
public function getProvidersByPackage($id = null) {
$package_id = $id;
$providers = ServiceProvider::whereHas('services', function ($query) use ($package_id) {
$query->where('package.package_id', $package_id);
})->get();
}

Related

magento shipping collectRates method $request->getDestRegionId() is empty value on estimate-shipping-methods-by-address-id

shipping collectRates method RateRequest class method of $request->getDestRegionId() is returning an empty value on estimate-shipping-methods-by-address-id, but same working well on estimate-shipping-methods
/V1/carts/mine/estimate-shipping-methods-by-address-id
from above API call in checkout $request->getDestRegionId() or $request->getDestRegionCode() is not working as expected.
public function collectRates(RateRequest $request)
{
if (!$this->getConfigFlag('active')) {
return false;
}
/** #var Magento\Shipping\Model\Rate\Result $result */
$result = $this->_rateResultFactory-create();
/** #var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
$method = $this->_rateMethodFactory-create();
$method->setCarrier($this->_code);
$method->setCarrierTitle($this-getConfigData('title'));
$method->setMethod($this->_code);
$method->setMethodTitle($this-getConfigData('name'));
$amount = $this->getShippingPrice();
$method->setPrice($amount);
$method->setCost($amount);
$region = ($request->getDestRegionId() !== null) ? $this-getStateNameByRegionID($request-getDestRegionId()) : $request-getDestRegionCode();
$result->append($method);
return $result;
}
Expecting same result like estimate-shipping-methods

Flatten laravel nested relationship (parent to descendants) get all childerns

This is my Controller
$categoryIds = Category::select('id')->with('childrenRecursive')->where('id', 1)->get();
Ad::whereIn('category_id', $categoryIds)->get();
This is my model
public function parent() {
return $this->belongsTo(Category::class, 'parent_id');
}
public function childs() {
return $this->hasMany(Category::class, 'parent_id');
}
public function Ads() {
return $this->hasManyThrough(Ad::class, Category::class, 'parent_id', 'category_id', 'id');
}
How get all childern categories ides
I solved this problem with this solution
My Controller
public function index()
{
$parent = Category::with('descendants')->find(1);
$descendants = $this->traverseTree($parent, collect([1]));
$ads = Ad::whereIn('category_id',$descendants)->get();
return response($ads);
}
protected function traverseTree($subtree, $des)
{
$descendants = $des;
if ($subtree->descendants->count() > 0) {
foreach ($subtree->descendants as $descendant) {
$descendants->push($descendant);
$this->traverseTree($descendant, $descendants);
}
}
return $descendants;
}
I'd do it with Laravel's Subqueries approach.
$parentId = 4;
Ad::whereIn('category_id', function($q) use ($parentId) {
$q->select('id')
->from('categories')
->where('parent_id', $parentId);
});
If you want to add the parent model, you can chain with():
Ads::whereIn('category_id', function($q) use ($parentId) {
$q->select('id')
->from('categories')
->where('parent_id', $parentId);
})
->with('category.parent')
->get();
Your code chunks are not clear so you may need to tweak my code example.
If I understand your question properly you need to get ads corresponding to id's of all related records also, for a given category record.
$category = Category::with('childs:id,parent_id')
->where('id', 1)
->firstOrFail();
$categoryIds = collect([$category->parent_id, $category->id]);
$category->childs->map(fn($child) => $categoryIds->push($child->id));
$ads = Ads::whereIn('category_id', $categoryIds->filter()->all())
// Can eager load the product(s) if needed
//->with('products')
->get();

Yii2 - Merge two models and return as JSON

In Yii2 Framework, is it possible to merge two models and return it as a one JSON object.
Below are the two object retrieved from database
public function actionJson()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$result = Result::findOne(1);
$user = User::findOne(1);
// Merge two objects
// Something like this
$model = $result + $user;
return $model;
}
You could assign the 2 to an associative array with key based on the model name
public function actionJson()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$result = Result::findOne(1);
$user = User::findOne(1);
//
$myModels['result'] = $result;
$myModels['user'] = $user;
return $myModels;
}
I got the answer. It's useful for someone
$myModels['result'] = $result->getModels();
$myModels['user'] = $user->getModels();

Yii2 - calling method on afterAction

I am trying to perform afterAction event in the controller, but nothing is happening (the function is not called). This is code for afterAction:
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
$this->_logDownloadActivity();
return $result;
}
And function I am trying to call:
private function _logDownloadActivity()
{
$model = new ActivityLogsUserActivity();
$model->user_id = Yii::$app->user->identity->id;
$model->userActivityType_id = 3;
$model->buildVersion = 3333;
$model->ipAddress = $model->userIP();
$model->insert();
}

How do I pass SQL database query from the Model to the Controller and then the View on Code Igniter 2.0.3?

I was trying to pass SQL values from Model to Controller but the value couldn't be passed.
This the code in my model file:
class Has_alert extends CI_Model {
function __construct()
{
parent::__construct();
}
function __get_query() {
$sql = 'alerts_get_alerts';
$query = $this->db->query($sql);
$row = $query->first_row();
$header_data['hasAlert'] = $row->active;
}
}
And this is the code in my controller file:
class Chart extends CI_Controller {
// Default Constructor
public function __construct() {
parent::__construct();
$this->load->helper('html');
$this->load->model('Has_alert', '', TRUE);
$this->Has_alert->__get_query();
//$sql = 'alerts_get_alerts';
//$query = $this->db->query($sql);
//$row = $query->first_row();
//$header_data['hasAlert'] = $row->active;
}
public function index()
{
//Data Arrays
$this->load->helper('html');
$header_data['page_title'] = 'Title';
$header_data['tabid'] = "home";
//Load the headtop.php file and get values from data array
$this->load->view('includes/headertop.php', $header_data);
$this->load->view('homepage');
$this->load->view('includes/newfooter.php');
}
I got this error message on my view file:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: hasAlert
Filename: includes/headertop.php
Line Number: 184
Does anyone know what the problem is? Thank you.
Model
function __get_query() {
$sql = 'alerts_get_alerts';
$query = $this->db->query($sql);
$row = $query->first_row();
return $row->active;
}
Controller
public function index(){
$this->load->model("Has_alert");
//Data Arrays
$this->load->helper('html');
$header_data['page_title'] = 'Title';
$header_data['tabid'] = "home";
$header_data['hasAlert'] = $this->Has_alert->__get_query();
//Load the headtop.php file and get values from data array
$this->load->view('includes/headertop.php', $header_data);
$this->load->view('homepage');
$this->load->view('includes/newfooter.php');
}
I'm assuming that things like "alerts_get_alerts" is pseudocode.