How to get Model Object using its name from a variable in Laravel 5? - class

I am trying to get information from a model using its name which is sent as parameter from blade using ajax call.
$.get("{{ url('auditInformation')}}", {modelName: modelName,versions:versions,currentData:currentData[index]});
Now i need to retrieve information using modelName from a model.
So when i tried this:
$auditInfo=Input::all();
$modelName=$auditInfo['modelName'];
$values=$modelName::find(1);
I got this response Class 'Designation' not found
But if i use
$modelName=new Designation();
$values=$modelName::find(1);
then it shows data exactly what i want.
So i understand that this is all about model ( class ) object.
Is there any way to assign object to $modelName using $auditInfo['modelName'] .
Thanks

If you want to do that way, you should use the model's namespace.
For example, if the 'Destination' model's namespace is app\Destination, you should use like this :
$auditInfo=Input::all();
$appPrefix = 'app';
$modelName=$appPrefix . '\' . $auditInfo['modelName'];
$values=$modelName::find(1);

This seems to be working
$table_name = "App\Models\PeopleYouMayLikeModel";
$obj = $table_name::where($column_name_identifier_1, '=', $row_identifier_1)
->where($column_name_identifier_2, '=', $row_identifier_2)->first();

The single backslash between the singe quote is considered as an escape sequence so use double backslash is 100% work. For example
public function index(Request $request) {
$model_prefix="App\Models";
$modal = $model_prefix.'\\'.$request->type;
$modal::updateOrcreate(['users_id'=>session("user")->users_id],$request->all())->save();
dd(Profile::all());
}
//Laravel 7.0

Related

Laravel Eloquent - How to manually append accessor/attribute to result

I have an accessor/attribute ( public function getGalleryAttribute() ) that adds an array of images to the model
I used to eager load this with: protected $appends = ['gallery'] , but I got rid of it to be able to control when I want to append the gallery or not.
I can append the gallery to a single model:
$event = Event::find(126)->append('gallery');
But how do I manually append an accessor when there is more than one result?
This doesn't work:
$events = Event::all()->append('gallery');
return $events;
error:
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::append does not exist
If you are using Eloquent 5.5 or later, you can use Collection::each to append to each item:
$events = Event::all()->each->append('gallery');
You should also look into Eloquent: API Resources to define alternative serialization options for the same model.

How to debug in TYPO3 if <f:debug> returns strings instead of object?

In a custom TYPO3 8.7.12 extbase extension I am unable to f:debug items in templates.
We are in the listAction controller and simply do:
$institutions = $this->institutionRepository->findAll();
$this->view->assignMultiple([
'institutions' => $institutions,
// ... pagination limit ...
]
);
And in the template:
<f:debug>
{institutions}
</f:debug>
This returns
sometimes the string 'Array' in the fluid debugger (can't reproduce now)
When the code is on 3 lines: #1273753083: Cannot cast object of type "TYPO3\CMS\Extbase\Persistence\Generic\QueryResult" to string.
Or also #1273753083: Cannot cast object of type "TYPO3\CMS\Extbase\Persistence\Generic\LazyObjectStorage" to string.
When the code is on 1 line: #1234386924: Cannot create empty instance of the class "TYPO3\CMS\Extbase\Persistence\ObjectStorage" because it does not implement the TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface.
If I loop through {institutions} with f:for and then f:debug:
<f:for each="{institutions}" as="institution" iteration="i">
<f:debug>
{institution}
</f:debug>
</f:for>
I get the first property of the object, e.g. the name.
EDIT: this is due to a __toString() magic method in the model. If I remove it, instead I get the namespace and uid STUBR\Extension\Domain\Model\Institution:55 – this looks again as if the object isn't rendered.
Wait... php.net says The __toString() method allows a class to decide how it will react when it is treated like a string. So could something be treating (typecasting?) the object as a string?
Working with the properties is normal, the issue just occurs when trying to print the whole object.
Where should I look? Lazy loading? There are some lazy loading properties, but not that many. Or maybe something is missing from the class? Or is there a workaround.
PS:
Unable to print_r or var_dump the query result, I get a memory limit error.
I saw https://wiki.typo3.org/Exception/CMS/1234386924 but initStorageObjects() is already called in the constructor
To answer the question;
<f:debug>{institutions}</f:debug>
will be parsed as an object, but any whitespace inside will make it parse as a string so.
The following methods do the same job as <f:debug> and work similarly in my case:
\TYPO3\CMS\Core\Utility\DebugUtility::debug(
$var = $variable,
$header = 'Institutions',
$group = ''
);
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump(
$variable,
$title = 'Institutions',
$maxDepth = 8,
$plainText = FALSE,
$ansiColors = TRUE,
$return = FALSE,
$blacklistedClassNames = NULL,
$blacklistedPropertyNames = NULL
);
execute in list or show action in controller.
It's less convenient than with f:debug (because you have to do the work in two different places, e.g. when you're in a loop in the template, you have to go to the controller and build that loop again), but it's a helpful workaround.
EDIT: I found it's sufficient to do
<f:debug>{var}</f:debug>
on one line

What is the best way to get the action name with Zend Framework

I'm pretty new to Zend digging the docs but i can't find a good way to get the parameter i passed to my action...
Here is my uri :
/entreprise/name/foo
I would like to extract the name, foo. I'm actually able to get the action name with
$this->getRequest()->getActionName();
or the URI with
$this->getRequest()->getRequestUri();
With these two data i can parse the second string and get the name of my entreprise, but i quite surprised there is no best way to do this...
Is there a best to way to it ?
Get the action name with:
$this->getRequest()->getActionName();
And additional data passed to this action by GET with:
$name = $this->_getParam('name', NULL);
This will get the GET-Value name if passed by URI, if not $name is set to null.
Edit:
As mentioned in the comments the way to pass vars is a bit different. Change it to
/entreprise/name/var/foo
And you'll be able to access foo this way:
$var = $this->_getParam('var', NULL);
In the following URI : /entreprise/name/foo if entreprise is your controller and name is your action, then the additional parameter will be used to call your action so you can get it by doing the following:
public function nameAction( $name = null )
{
// $name == "foo"
}

How to use Zend Framework's Partial Loop with Objects

I am quite confused how to use partialLoop
Currently I use
foreach ($childrenTodos as $childTodo) {
echo $this->partial('todos/_row.phtml', array('todo' => $childTodo));
}
$childrenTodos is a Doctrine\ORM\PersistantCollection, $childTodo is a Application\Models\Todo
I tried doing
echo $this->partialLoop('todos/_row.phtml', $childrenTodos)
->setObjectKey('Application\Models\Todo');
But in the partial when I try to access properties/functions of my Todo class, I cant seem to get them always ending up with either call to undefined method Zend_View::myFunction() when I use $this->myFunction() in the partial or if I try $this->todo->getName() I get "Call to a member function getName() on a non-object". How do I use partialLoops?
Try this
echo $this->partialLoop('todos/_row.phtml', $childrenTodos)
->setObjectKey('object');
Then in your partial you can access the object like this
$this->object
object is the name of the variable that an object will be assigned to
You can also do this once in your Bootstrap or other initialization class if you have access to the view object like so
protected function initPartialLoopObject()
{
$this->_view->partialLoop()->setObjectKey('object');
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->setView($this->_view);
}
I also had "Call to function on non object" error when trying suggested syntax, seems like they've changed something on later versions of Zend Framework. The following works for me on ZF1.12:
echo $this->partialLoop()
->setObjectKey('object')
->partialLoop('todos/_row.phtml', $childrenTodos);

CodeIgniter: URIs and Forms

I'm implementing a search box using CodeIgniter, but I'm not sure about how I should pass the search parameters through. I have three parameters: the search string; product category; and the sort order. They're all optional. Currently, I'm sending the parameters through $_POST to a temporary method, which forwards the parameters to the regular URI form. This works fine. I'm using a weird URI format though:
http://site.com/products/search=computer,sort=price,cat=laptop
Does anyone have a better/cleaner format of passing stuff through?
I was thinking of passing it into the products method as arguments, but since the parameters are optional things would get messy. Should I suck it up, and just turn $_GET methods on? Thanks in advance!
Query Strings
You can enable query strings in CodeIgniter to allow a more standard search function.
Config.php
$config['enable_query_strings'] = FALSE;
Once enabled, you can accept the following in your app:
http://site.com/products/search?term=computer&sort=price&cat=laptop
The benefit here is that the user will find it easy to edit the URL to make a quick change to their search, and your search uses common search functionality.
The down side of this approach is that you are going against one of the design decisions of the CodeIgniter development team. However, my personal opinion is that this is OK provided that query strings are not used for the bulk of your content, only for special cases such as search queries.
A much better approach, and the method the CI developers intended, is to add all your search parameters to the URI instead of a query string like so:
http://site.com/products/search/term/computer/sort/price/cat/laptop
You would then parse all the URI segments from the 3rd segment ("term") forward into an array of key => value pairs with the uri_to_assoc($segment) function from the URI Class.
Class Products extends Controller {
...
// From your code I assume you are calling a search method.
function search()
{
// Get search parameters from URI.
// URI Class is initialized by the system automatically.
$data->search_params = $this->uri->uri_to_assoc(3);
...
}
...
}
This would give you easy access to all the search parameters and they could be in any order in the URI, just like a traditional query string.
$data->search_params would now contain an array of your URI segments:
Array
(
[term] => computer
[sort] => price
[cat] => laptop
)
Read more about the URI Class here: http://codeigniter.com/user_guide/libraries/uri.html
If you're using a fixed number of parameters, you can assign a default value to them and send it instead of not sending the parameter at all. For instance
http://site.com/products/search/all/somevalue/all
Next, in the controller you can ignore the parameter if (parameter == 'all'.)
Class Products extends Controller {
...
// From your code I assume that this your structure.
function index ($search = 'all', $sort = 'price', $cat = 'all')
{
if ('all' == $search)
{
// don't use this parameter
}
// or
if ('all' != $cat)
{
// use this parameter
}
...
}
...
}