Calling Model->Method() within blade templates - laravel

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.

Related

How to get the property value in Laravel Blade that was transformed by Eloquent API Resource?

Currently, my solution to display an encoded ID is like that:
<p v-text='"Reservation code: "+ #json($orderJson).id'></p> //R. code: wYeyjo6l42
But I would prefer to use it like:
<p>#json($orderJson->id)</p> //but returns: 8 (not encoded)
How can I get the transformed attributes?
p.S. Yes I know it's used for API, but I'm even using it to handle objects to Vue via Blade.
Well, I dug up in the code and found out you can use resolve().
So one solution would be:
<p>Reservation code: {{ $orderJson->resolve()['id'] }}</p>

Is there something similar to Twig filters that I can use in Laravel Blade

Twig has this awesome feature called Twig Filters which allow you to change the variables that you send to your view, from within the view without messing with the data model.
{ variable_name | filter_name }
This makes it super-duper readable and clean. Filters can be lowercase, encoding, raw text or you can build your own.
Question is simple: I really miss this kind of functionality, what's the best way to implement something like this in Laravel using Blade?
as i know Blade don't offer this functionality of filters, but u can create a helper file that can has many functions helper and every function has her logic.
in this link u can find how to create a helper file with functions and call them inside ur blade file tutorial how to create helper function

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.

way to pass variable through url in codeigniter

I got a big search module in my Codeigniter project. Well simply I am passing variable to a view like
<a href=<?php echo site_url('controller/view/1'); ?>>View List</a>
And fetching its data in controller like
$id=$this->uri->segment(3);
For pagination
http://wwww.site.com/controller/view/<filter id>/<page from>
This is working perfectly in the case of simple query.
Now I got some more filter quires like
Country
State
City
Customer type
etc etc
then the url should be
http://wwww.site.com/controller/view/1/id2/id3/i4/id5
Is this the correct way to do the process ? If not please give a little advice...
I am new to codeigniter
The problem you are facing i have recently found a solution for this.
When you are first sending parameters through url use POST instead.
When you get the parameters you can pass them to session in a variable
type. Next time when you paginate get the type value from session and
put it in your query to get the desired result.
If you have more than 1 parameters you can put them in sessions and
unset them on certain conditions so that they are not called in every query.
I think the best approach here is to create another method in the controller something like filtered_view that accepts a filter_id and a page number, and that methode will fetch the data from the database with the provided filter and you'll use your pagination class as usual.
Hope this help.

Resources