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.
Related
I developed a Laravel application that connects to a external MySQL database for reports. I'm using Maatwebsite/Laravel-Excel 3.1 to be able to export to excel.
In this app, I have a method in my model that uses Input::get() for 3 variables ($from, $to, $paymentType). This method is called whenever the user chooses date range and payment type as filter for their reports. Everything works as it should since data is displayed in my view.
Now this same method is called when the user chooses to export the file to excel. Again, all that works except the files is blank.
The curious thing is that if I replace all Input::get() for static values such as '2018-11-14' for the dates and 'n' for payment type, then the file exports with data.
I've been struggling with this for a couple of days so I hope someone can help me.
Thanks,
Ernesto
First, towards the top of the controller file, add:
use Illuminate\Http\Request;
Then, you can access the fields by:
$request->input('from');
$request->input('to');
Assumption: from and to are correct field names.
You can also use request()->input('from') etc. directly (note the absence of $).
Please see this for more info: https://laravel.com/docs/5.6/requests
If the parameters are obtained from the request you should use $request->input() instead of Input::get().
If used in a function where $request is not available you could use request('variable') to get the variable value from the request.
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.
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.
I asked this on the Laravel 4.x forum and tried to find the answer on Google without any luck.
I'm using Eloquent to load a bunch of user objects that have a created_at property. The default MySQL timestamp isn't very readable, so I thought it would be neat to add a readableDate() method to my User model which would output the value as "1 minute ago", "2 days ago" instead.
When I call on the method in my blade templates like: $user->readableDate() I get the desired output but my whole layout is broken.
Is it, or should it be possible to call on a model method from within a template?
If you're using Laravel's Eloquent models, you do not need to add custom methods for handling dates. By default, date fields such as created_at and updated_at are handled as a Carbon objects, which allows you to display the date in a human readable format:
{{ $user->created_at->diffForHumans() }}
You can add additional date fields to your Eloquent model with the getDates() method.
Yes, blade is compiled to PHP. :)
You just have to:
Pass your user to your view:
return View::make('showUser')->with('user', $user);
And then use it:
<hml><body>
Last update: {{ $user->readableDate() }}
</body></hml>
Can I assume you are wrapping it inside blade tags {{ code here }}, or did you miss that part?
Also, your model should be called using the static approach like this:
{{ User::readableDate() }}
ok, I figured this out. What I was trying to do is possible but it was throwing an error that I couldn't see. When I viewed the source of the page the usual laravel error HTML was below my output. The error was being thrown by default values in the created_at field.
Actually I am working on a FLOW3 project and up to now it´s really great fun working with FLOW3, even if the documentation is not that good. But now I have problem: I want a JavaScript/jQuery function inside my frontend to call a controller action and the controller to return a json. As there is not much about this inside the documentation I tried a the way like in http://bytelude.de/2012/09/10/flow3-wie-erstelle-ich-eine-ajax-action-mit-json-ruckgabe/, but I always got a answer from the application that there is no view defined. I am using FLOW3 1.1.0. Maybe someone can give me a hint how to perform a ajax/json camm in a simple way.
FLOW3 now uses Mime-Types instead of formats: The second example in the Json View Section should do the trick.
You have to set
protected $supportedMediaTypes = array('application/json', 'text/html');
instead of
protected $supportedFormats = array("html", "json");
now.
Maybe you need to check your Route.yaml, if you set the format to json, does it change something ?
If you do not want to bother with Json-Views and Mime-Types you can always just do this in your controller:
return json_encode($data);
When you return something (a string) in the Controller-Action, the view is never queried and the return gets used instead.