Accessing model from controller? - laravel

I want to get data from my database and then in my model I wish to do some php stuff to the data before passing it to my view.
Normally I would do this to get all of my data:
->with('content', Content::all());
But I have set up a function in my model called test:
public function test(){
//get and modify data here
}
How can I access this using:
->with
from my controller?

Is this the one you are looking for?
Model:
public static function foo($bar) {
return static::where('foo', '=', 'bar');
}
Controller:
->with('content', Foo::foo("test"));

What you are trying to do isn't really explained correctly but I'll try to answer anyway.
From what I understand, you want to do some data transformation in the model before it is used. But your comment in the test() function say that you want to GET and modify data.
In laravel, functions for getting and modifying data are separated:
For getting data, you can define a query scope ( http://four.laravel.com/docs/eloquent#query-scopes ). A query scope is usually a shortand for adding some parameters to an existing query.
For modifying data before it is read from the model, or before assinging it to the model, Eloquent provide a system called mutators (http://four.laravel.com/docs/eloquent#accessors-and-mutators ). A mutator is a method called when reading or assiging value to a field. It is usualy to convert php type to a database type (for example array to json on save, then json to array on read). A mutator can be used to populate some extra value or do some extra checks to the value.
I hope I've helped you a bit. If you don't find it is a correct answer, please clarify your question so I can help you a little more.

Related

How to use relationship data outside of relationship field in Laravel Nova?

I am trying to figure out how to do something seemingly simple with Laravel Nova, but I can't figure this out.
What I want to do is reference relationship data in a text field. I see in Nova, and understand how to reference a relationship via the HasOne, HasMany ... facades. But what I want to do is get relationship data like this:
Text::make('State', $this->state->name)
This doesn't work, and something I noticed when trying to debug is that each function in a Nova resource seems to run multiple times. Here is the logging I added:
public function fields(Request $request) {
logger($this->state->name)
}
When I do this, there are 3 logging instances, the first 2 containing the state name, and the third not. I think that may have something to do with it not working, but don't know what might be causing this.
Thank you in advance for help!
There's a simple way to get relationship data into a Nova Text field, just use a closure:
Text::make('State', function() {
return $this->state->name;
})
As for the multiple calls to the fields function, the answer has to do with the question: Do you have another Resource in your Nova folder that is related to the Resource we are discussing? If so, that is why -- it needs to call fields to display it properly. You can examine the following query string parameters to get more insight: viaResource, viaResourceId, and viaRelationship.

Why is my Laravel Eloquent accessor not showing up in the response?

I have a Model Review that has a unix timestamp as 1 of it's attributes (table columns).
I use 2 accessors inside this model:
public function getReviewDateAttribute($value)
{
return strftime('%A %e %B %Y', $value);
}
public function getReviewDateIsoAttribute()
{
return Carbon::createFromTimestamp($this->review_date)->toDateTimeString();
}
getReviewDateAttribute works as expected and shows up in the collection of models when I write a query.
However getReviewDateIsoAttribute does not. What could be the reason for this?
A subquestion: If I use the same attribute in both functions, how can I use the original format as input value?
You should be adding it to the $appends array. It isn't spinning through all available methods looking for getXXXXXAttribute. The other one is used because it is an accessor for an actual attribute, this one is not an actual attribute.
class YourModel ....
{
protected $appends = ['review_date_iso'];
...
}
Laravel 5.5 Docs - Eloquent - Serialization - Appending Values to JSON
This is probably because ReviewDateIso is not an actual column and therefore will not show up in the model collections...you can access it directly by calling the method directly
$model->getReviewDateIsoAttribute()
According to the docs accessors a ways of changing the value of a column before it is returned to the method that queried it.
If you want it to show up when you call the collection as Json append it to the output with
protected $appends = ['name_of_attribute'];
I tried queries in tinker and with dd method. So I got confused since I cant view my new accessor in the attribute list.
I thought I missed something. Then later I noticed appended attributes are shown separately when we dd the query result than the usual attribute JSON.
I lost time thinking my accessor is not working. Its just I`m not checking in the right way or right place. So I``m attaching the following image, if anyone gets stuck on accessors like me, this might help them.
In fact it depends on what you are trying to achieve. If you are going to display anything in Blade for example, you can use whenever you want $object->review_date_iso to get this attribute value.
However if you are returning Json responses (for example API), you need to tell Eloquent model to append extra fields to your model when transforming to JSON format.
You probably have review_date attribute in your model (this is the column in database I suppose) but you don't have review_date_iso in your table in database, so in your model you need to use:
protected $appends = ['review_date_iso'];
but you don't have to include here review_date because it's already in your table in database and your accessor will be automatically fired.

Laravel 4 - Unable to override getDateFormat()

Can anyone tell me why I get an error saying Trailing Data, whenever I Override this method in my model and alter it in any way?
protected function getDateFormat() {
return 'Y-m-d H:i:s';
}
Any change to the above code breaks my page.
I am following the official documentation here: http://laravel.com/docs/eloquent#timestamps
getDateFormat is purely meant for how date/time fields are stored in the database. You're not meant to modify it for display purposes.
EDIT: Here are some suggestions for custom formatting of your datetime fields if you don't want to call format() everywhere.
Make a presenter class
Add accessor methods like getDateYearAttribute and getDateMonthAttribute
Use Carbon's setToStringFormat method as documented here
Add a HTML macro for formatting dates
Add a blade extension for the same thing
This may not be the same but I would get this error when working with timestamps and carbon but using strtotime() on the data i was passing resolved my issue, may help you.

Other way to pass data from block to controller Magento

I'm pretty new to PHP programming and Magento. I wanna to pass the current ProductId from a form within a custom block to a controller (new action).
Yes I know that one method would be to add an input hidden (with my product id) in the custom block form and then to retrieve the Value through a regular:
$this->getRequest()->getPost('myvalue'))
Is there a better way in Magento to retrieve the value within the controller without having to declare extra secret input fields ?
Good for you for wanting to adhere to best practices within Magento! The passing of data to controllers is pretty standard, however. If we look at how the product is added from a product page, we'll actually see the product ID in the form action URL's parameters:
http://domain.com/checkout/cart/add/uenc/uenc_value/product/45573/
...where 45573 is the product ID. Of course this can also be sent to the controller via a hidden input field, which I use all the time. Note that the above is the same as http://domain.com/checkout/cart/add/?uenc=uenc_value&product=45573 in Magento.
Another way of storing data for use in controllers for future use is setting data into a session. For posting data to a controller I wouldn't recommend this method but it's something to keep in mind:
$session = Mage::getSingleton('core/session');
$session->setMyValue(true);
We can then retrieve the data from my_value later just by instantiating the session. Good luck!
Passing your data could be done in different ways :
You could use Magento's magic setters and getters.
So you would have to do this to set the value :
Mage::getSingleton('core/session')->setSomeVariable($value);
and this to retrieve it :
Mage::getSingleton('core/session')->getSomeVariable();
Or you could use the register.
Mage::register('key', $value); //to set your data
Mage::registry('key'); //to get your data
Magento provides a way to construct a URL with the necessary values, calculated against the configuration DOM. Blocks (and therefore block templates) can call Mage_Core_Block_Abstract::getUrl() directly:
$this->getUrl('some_handle/foo/test',array('id'=>'some_value'));
// Mage::getUrl() will work as well
The above would result in the following URL:
http://base_url/frontname/foo/action/id/some_value/
...which can be read in the FooController testAction() as
$this->getRequest()->getParam('id') // 'some_value'

Passing form data through MVC - Joomla

I'm creating a search form that shows a single user depending on the exact match of the first and last names and a member ID. I have the component shell set up with the form data going to a custom controller in 'com_medsearch/controllers/search.php'. I've read the tutorials in the Joomla docs, but I'm not sure how to pass the data to the model (com_medsearch/models/search.php) and the query results back to the same view. Answers?
You can do this 2 ways:
You detect that you had a search post in your controller then you call your model and in the model you can use JRequest::getVar / getInt / etc to read your variables.
You detect your search post and read your variables from the post all in your contoller function and pass it to your model.
Here is an example for point 2:
$settings = JRequest::get( 'POST' );
$model = & $this->getModel('settings');
$model->saveSettings($settings);
Then in your model you can access your post variables like:
$settings->input_name

Resources