i try use __call magic method for make dynamic method in laravel Eloquent.
i have blog and blog_translations table and TITLE,CONTENT must be load from blog_translations table .
public function translations($lang = null)
{
if(empty($lang)) {
if (!empty(Lang::getLocale())) {
$language = Lang::getLocale();
} else {
$language = Config::get('app.fallback_locale');
}
}else{
$language = $lang;
}
return $this->hasMany(Blog_Translation::class)->where('locale', $language);
}
public function __call($method,$arg)
{
$filed = str_replace('get','',$method);
if(sizeof($arg) >= 1){
$lang = $arg[0];
}else {
$lang = '';
}
return $this->translations($lang)->where('name',$filed)->first()->text;
}
in controller :
$blog = Blog::find(1);
return $blog->getTITLE();
error :
Undefined property:
Illuminate\Database\Eloquent\Relations\HasMany::$id
with remove __call function relationship work good.
Related
If I try this is a class with static methods:
public static function chkLog($role)
{
$userrole = $this->getRequest()->getSession()->read('userrole');
return $userrole;
/// more code
Even tried:
public static function chkLog($role)
{
$userrole = Session::read('userrole');
return $userrole;
/// more code
In laravel I can:
public static function userRole($role = null)
{
$userrole = Auth::user()->role;
$checkrole = explode(',', $userrole);
if (in_array($role, $checkrole)) {
return $role;
}
return false;
}
usage
public function scopegetPets($query, $petsearch = '')
{
$petsearch = $petsearch . "%";
$query = Pet::where('petname', 'like', $petsearch);
if (ChkAuth::userRole('admin') === false) {
$userid = Auth::user()->id;
$query->where('ownerid', '=', $userid);
}
$results = $query->orderBy('petname', 'asc')->paginate(5);
return $results;
}
But in cakephp to call statically I had to write this:
public static function __callStatic($method, $params)
{
$instance = ChkAuth::class;
$c = new $instance;
return $c->$method(...array_values($params));
}
In order to call this:
public function userRole($role = null)
{
$userrole = $this->getRequest()->getSession()->read('userrole');
$checkrole = explode(',', $userrole);
if (in_array($role, $checkrole)) {
return $role;
}
return false;
// more
And usage:
public function getPets($offset = "", $rowsperpage = "", $petsearch = "")
{
$pagingQuery = "LIMIT {$offset}, {$rowsperpage}";
$petsearch = $petsearch . "%";
if (Auth::chkRole('admin') === true) {
return DB::select("SELECT * FROM " . PREFIX . "pets " . $pagingQuery);
}
$authid = Auth::authId();
return DB::select("SELECT * FROM " . PREFIX . "pets WHERE ownerid = :authid " . $pagingQuery, ["authid" => $authid]);
}
So basically I am trying to figure out how to use session in cake php inside a static method.
Note the __callStatic works, but as a work a round.
CakePHP's Router class includes a static function to return the request object. The request object includes a function to return the session. So:
Router::getRequest()->session()
or, as of version 3.5:
Router::getRequest()->getSession()
In the following code, the function parseImages is not implemented.
Can someone help me to call the function parseImages in the foreach:
foreach ($listFeatured as &z$product) {
$product['description'] = substr(trim(strip_tags($product['description_short'])), 0, $maxDesc);
$product['price'] = Tools::displayPrice($product['price']);
$product = $this->parseImages($product, $params);
$product = $this->generateImages($product, $params);
}
function parseImages($product, $params) {
global $link;
$isRenderedMainImage = $params->get("cre_main_size", 0);
if (_PS_VERSION_ <= "1.5.0.17") {
$mainImageSize = $params->get("main_img_size", 'thickbox');
} else {
$mainImageSize = $params->get("main_img_size", 'thickbox_default');
}
if ($isRenderedMainImage) {
if ((int) Configuration::get('PS_REWRITING_SETTINGS') == 1) {
$product["mainImge"] = $this->getImageLink($product["link_rewrite"], $product["id_image"]);
} else {
$product["mainImge"] = $link->getImageLink($product["link_rewrite"], $product["id_image"]);
}
} else {
$product["mainImge"] = $link->getImageLink($product["link_rewrite"], $product["id_image"], $mainImageSize);
}
$product["thumbImge"] = $product["mainImge"];
return $product;
}
This is a piece of a module of Prestashop and I want to use it twice.
If solved I will share the solution to all Prestashop users.
You're using as an object method $this->parseImages() but you defined it as a function:
function parseImages($product, $params) {
[...]
}
You can keep this function like this and use parseImages() without the $this-> or if you're inside a class change your function declaration to this:
public function parseImages($product, $params) {
[...]
}
You should read some documentation about OOP
Ok so I currently have this Controller which basically retrieves a Model and does some calculation.
Original code has tonnes of calculation but this is a trimmed down version for simplicity.
I wanted to move all logic to the Model and have built the code below it so far but can not figure out how to pass the custom messages to the Controller.
I am a beginner in Laravel so trying to achieve this in an easy to understand way so I can maintain it and managed to get the code below working but without custom error messages being passed onto the Controller.
Can you give me an example code of how you are passing custom error messages to controller
This is the original code in controller.
Controller
public function getDetail()
{
$request = Model::where('id','=',8)->first();
if($request)
{
if($request->number >= 5)
{
return Redirect::back()->withMessage('You have 5 or more');
}
if($request->number > 0 && $request->number < 5)
{
return Redirect::back()->withMessage('You have between 1 and 4');
}
if($request->number <= 0)
{
return Redirect::back()->withErrors('You do not have enough points');
}
}
else
{
return Redirect::back()->withErrors('No details found');
}
}
This is the new code I tried to build to move logic to model but could not figure out how to pass the custom error messages along?
Model
Class Profile
{
private $model
function __construct()
{
$this->model = Model::where('id','=',8)->first();
}
public function Notification()
{
if($this->model->number >=5)
{
return true;
}
if($this->model->number > 0 && $this->model->number < 5)
{
return true;
}
if($this->model->number <=0)
{
return false;
}
}
}
Controller
public function getDetail()
{
$request = new Profile;
$result = $request->Notification();
if($result)
{
return Redirect::back()->withMessage(????????);
}
else
{
return Redirect::back()->withErrors(????????);
}
}
Just return the message from the Model function and use it in the controller to return like shown below.
Model function
public function Notification()
{
$returnArray = array();
if($this->model->number >=5)
{
$returnArray['isMessage'] = true;
$returnArray['message'] = "You have 5 or more";
}
if($this->model->number > 0 && $this->model->number < 5)
{
$returnArray['isMessage'] = true;
$returnArray['message'] = "You have between 1 and 4";
}
if($this->model->number <=0)
{
$returnArray['isError'] = true;
$returnArray['error'] = "You do not have enough points";
}
return $returnArray;
}
Controller function
public function getDetail()
{
$request = new Profile;
$result = $request->Notification();
if(isset($result['isMessage']) && $result['isMessage'] == true)
{
return Redirect::back()->withMessage($result['message']);
}
else if (isset($result['isError']) && $result['isError'] == true)
{
return Redirect::back()->withErrors($result['error']);
}
}
Ideally speaking you should not create an object of Model in controller. You can just create the function as a static method inside model and call it from controller.
I'm trying to pass multiple parameters in a url that looks like this...
http://somedomain.com/lessons/lessondetails/5/3
... to a function in the controller that looks like this ...
class LessonsController extends Controller
{
public function lessonDetails($studentId, $editRow=NULL)
{
try {
$studentData = new StudentsModel();
$student = $studentData->getStudentById((int)$studentId);
$lessons = $studentData->getLessonsByStudentId((int)$studentId);
if ($lessons)
{
$this->_view->set('lessons', $lessons);
}
else
{
$this->_view->set('noLessons', 'There are no lessons currently scheduled.');
}
$this->_view->set('title', $student['first_name']);
$this->_view->set('student', $student);
return $this->_view->output();
} catch (Exception $e) {
echo "Application error: " . $e->getMessage();
}
}
}
But only the first parameter seems to pass successfully.
Not sure what to copy and paste here but here's the bootstrap.php...
$controller = "students";
$action = "index";
$query = null;
if (isset($_GET['load']))
{
$params = array();
$params = explode("/", $_GET['load']);
$controller = ucwords($params[0]);
if (isset($params[1]) && !empty($params[1]))
{
$action = $params[1];
}
if (isset($params[2]) && !empty($params[2]))
{
$query = $params[2];
}
}
$modelName = $controller;
$controller .= 'Controller';
$load = new $controller($modelName, $action);
if (method_exists($load, $action))
{
$load->{$action}($query);
}
else
{
die('Invalid method. Please check the URL.');
}
Thanks in advance!
Call $this->getRequest()->getParams() from your action controller and check if both parameters are there.
If NO, the problem lies with your routing.
If YES, the problem lies with passing the parameters to your controller method lessonDetails.
Also, lessondetailsAction is missing. (this will be the method called if you visit the url you posted)
I have two controllers, one is base controller, other is subject in the base controller I defined some arrays from Model, look:
class Controller_Base extends Controller_Template {
public $template = 'main';
public function before()
{
parent::before();
$webs = array();
$apps = array();
$app = new Model_Application();
$apps = $app->get_all();
$web = new Model_Web();
$webs = $web->get_all();
$this->template->content = '';
$this->template->styles = array('style');
$this->template->scripts = '';
$this->template->webs = $webs;
$this->template->apps = $apps;
}
}
in the controller subject I am using function in_array
class Controller_Subject extends Controller_Base {
public function action_all()
{
$url = $this->request->param('url');
$this->template->caption = $url;
if (in_array($url,$this->template->webs)) {
echo "web";
}
elseif (in_array($url,$this->template->apps)) {
echo "apps";
}
$links = array("a"=>"1","b"=>"2");
$view = View::factory('subject')
->set('links',$links);
$this->template->content = $view;
}
}
but the Kohana returns me an error:
ErrorException [ Warning ]: in_array() [<a href='function.in-array'>function.in-array</a>]: Wrong datatype for second argument
Whats wrong?
You need array variables instead of Database_Result objects:
...
$apps = $app->get_all()->as_array();
...
$webs = $web->get_all()->as_array();
...
The Models returned data, that is, Database_MySQL_Result, needs to be changed to an array first.
you can use
foreach($query as $v)
$arr[]=$v;
return $arr;
in your get_all().