im trying to format datetime values in laravel to make them match with sql server format, im getting this error:
The separation symbol could not be found Unexpected data found.
Unexpected data found. Trailing data
Im using a custom format in my model:
protected $dateFormat = 'd-m-Y H:i:s';
It works good for the create method con controllers, there is no problem, the error happen when try to update and I think is related to how the value is stored in the database.
Using tinker I retrieve the value of updated_at in my model and is shown in the next format:
updated_at: "2018-07-24 09:14:09.000"
So when Im updating this value the format used is:
protected $dateFormat = 'd-m-Y H:i:s';
I think it should be something like d-m-Y H:i:s.000 but doesnt work, how can I solve this?
I had exactly the same issue, when switching to laravel version 5.6. Now I found the correct way to handle this.
Create a Base class like this and add a public method getDateFormat.
There you return the date a little bit different
return 'Y-d-m H:i:s.v';
See that date (d) and month (m) are switched and at the end you need to put a .v which stands for milliseconds. This worked for me fine. See here my complete Base class:
<?php
namespace App\Models\Base;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model
{
public function getDateFormat()
{
return 'Y-d-m H:i:s.v';
}
public $timestamps = false;
}
What version of Laravel are you using? This was fixed in a recent release (can't remember exactly which) that relies on PHP 7.
The dateFormat should be "Y-m-d H:i:s.v". v is Milliseconds (added in PHP 7.0.0). The problem you're experiencing with updates and inserts is caused when the updated/inserted model is returned. It is passed to Carbon to convert date and datetime fields into instances of Carbon, but the datetime fields have 'trailing
You can also try this one in SQL/Select Query:
\DB::raw ("DATE_FORMAT(comments.date,'%d-%m-%Y %H:%i:%s') as sth_date")
E.g:
Comment::orderBy('date','desc')->with('user')
->join('users','comments.id_user', '=', 'users.id')
->select('users.username', 'comments.id', 'comments.id_race', 'comments.status', 'comments.ip_address', 'comments.id_user',
\DB::raw ("DATE_FORMAT(comments.date,'%d-%m-%Y %H:%i:%s') as sth ") );
Time fraction is a configuration of your database, you can see it below, so you can just try to switch on your database.
https://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html
But using something like $d->format("Y-m-d H:i:s.u") you can format/manipulate using class Datetime().
Related
I recently updated an old laravel 5.7 project to 8.0 and the created_at and updated_at model timestamps get created with the wrong format. Back in the day i used this code in all models that are from a SQL Server database to get it working between my local and production environment.
public function getDateFormat()
{
if (PHP_OS_FAMILY == 'Windows') {
return 'Y-d-m H:i:s.v';
} else {
return 'Y-m-d H:i:s';
}
}
I use windows to develop the application and a Linux server to run it with apache, but after updating the project the timestamps invert the day and month of the date. For example, if i create a model in the date '2022-06-07 13:00:00' the created_at timestamp will be '2022-07-06 13:00:00'.
Of course, changing the getDateFormat() method to only return 'Y-d-m H:i:s.v' in all environments works, but create another problem with php date function, for example, if i call <p> updated at: {{ date('d/m/Y H:i:s', strtotime($model->updated_at)) }}</p> the desired result would be updated at: 07/06/2022 13:00:00 but instead i get updated at: 06/07/2022 13:00:00.
I really dont know if this is a php timezone issue or something related to laravel, since the problem shows at saving/updating rows or displaying formatted data information.
try
date("Y-d-m H:i:s", time());
Please use:
updated at: {{ date('m/d/Y H:i:s', strtotime($model->updated_at)) }}
for the desired result as the above m shows month, d shows days similarly y shows year.
Laravel have Carbon so use it for datetime stuff
use Carbon\Carbon;
...
if(! function_exists('format_date') {
function format_date(string $date): string
{
return Carbon::parse($date)->format('d-m-Y H:i:s');
// something like 31-12-2022 12:00:00, just change format as you need
}
}
From your view:
{{ format_date($model->date) }}
Make sure to check Ref
I want to get a timestamp that is represented in milliseconds or seconds in order to convert it to a DateTime javascript object on the frontend. If there is a way to convert this format
"timestamp" : "2020-11-06T10: 51: 10Z" to a javascript DateTime object just tell me. If I need to use a separate serializer for the DateTime, how do I use a serializer in a serializer?
You can override the to_representation method in your serializer if you don't like the default string representation:
class YourSerializer(serializers.ModelSerializer):
class Meta:
model = YourModel
fields = ['id', 'your_datetime_field']
def to_representation(self, instance):
formatted_datetime_field = instance.your_datetime_field.timestamp()
return {'id': instance.id,
'your_datetime_field': instance.formatted_datetime_field}
This will give you the Unix time, in seconds. JavaScript's Date objects work in milliseconds so you can multiply the result by 1000 to make it work on the frontend.
A slightly different but in my opinion more simple solution would be:
date = serializers.SerializerMethodField(method_name='get_date_timestamp')
def get_date_timestamp(self, instance):
return instance.date.timestamp()
Hi i am working on a project in laravel 7.0, in back-end i have a table called Posts which contains 2 text language input one in french and the other is arabic added by the back-end application.
what i am trying to do is when the user uses the French Language i want the title_fr to be displayed on the view and same thing in Arabic language the title should be title_ar.
P.S data are stored in French and Arabic
I have tried the similar solution given in an other similar question but none of it worked in my case!
Any idea how i might get this to work ?
Thanks in advance.
You can do something similar to below. We have a model Post, this model has an attribute title. I also assume that you have an attribute that will return user's language from the User model.
class Post extends Model
{
public function getTitleAttribute(): string
{
return Auth::user()->language === 'fr' ? $this->title_fr : $this->title_ar;
}
}
FYI above is just a demo on what can be done. For a full blow solution I would recommend decorator pattern.
Also it might be worth considering using morph for things like that. You can have a service provider that will initiate the morph map for you post model relevant to the language that user has, I.e.
Class ModelProvider {
Protected $models = [
‘fr’ => [
‘post’ => App/Models/Fr/Post::class,
],
‘ar’ => [
‘post’ => App/Models/Ar/Post::class,
]
];
Public function boot() {
$language = Auth::user()->Settings->language;
Relation::morphMap($This->models[$language]);
}
}
Afterwards you just need to call to Relation::getMorphModel(‘post’) to grab Post class that will return correct language.
I.e. App/Models/Fr/Post can have a an attribute title:
Public function getTitleAttribute(): string {
Return $this->title_fr;
}
For example above you would also want to utilise interfaces to make sure that all models follow the same contract, something below would do the trick:
Interface I18nPostInterface {
Public function getTitleAttribute(): string
}
Also, depending on the database you use, to store titles (and other language data) in a JSON format in the database. MySQL 8 has an improve support for JSON data, but there are limitations with that.
So I was Able to fetch data from my database based on the Language selected by the user.
Like i said before I have a table called Posts and has columns id,title_fr and title_ar. I am using laravel Localization.
Inside my PostController in the index function i added this code:
public function index()
{
//
$post = Post::all();
$Frtitle = post::get()->pluck('title_fr');
$Artitle = post::get()->pluck('title_ar');
return view('post.index',compact('post','Frtitle','Artitle'));
}
if anyone has a better way then mine please let me know, i am sure
there is a better way.
I have read and worked with the other posts about this and it appears the version of Laravel 4 I just downloaded has more changes made to the way the JSON input is handled by a controller.
$input = Input::json()->all(); gives me errors as if I am referring to something that does not exist when I request some part of the payload after doing a PUT request. And without ->all(); I get a symfony error.
Does anyone know how to get good JSON from backbone in Laravel 4's latest version?
Currently, I am doing the long way around to get my data, ie:
$input_title = Input::get('title');
$input_completed = Input::get('completed');
$task = Task::find($id);
$task->title = $input_title;
$task->completed = $input_completed;
$task->save();
Yes, I am doing the tutorial on tutsplus to learn laravel/backbone, so a little noob patience is apreciated.
The error I get when using Input::get(); is:
{"error":{"type":"UnexpectedValueException","message":"The Response content must be a string or object implementing __toString(), \"array\" given.","file":"/Users/brentlawson23/Sites/laravel4App/bootstrap/compiled.php","line":16858}}
I really want to get the Laravel-specific answer instead of using straight php to stringify the payload.
I get same error using just Input::json();
For the current beta of Laravel 4, Input::json(); is not getting a stringified version of the request payload that can be used to create a new row in a table, nor does Input::json()->all(); (hoping to play nice with the ParameterBag from symfony). I have tried json_encode among other hacks and basically every step of the way in this tut, I hit some brick wall. Anyone have a suggestion based on what I have presented here?
Today I got this when simply trying to echo the result of $input = Input::json(); :
{"error":{"type":"ErrorException","message":"Catchable Fatal Error: Object of class Symfony\Component\HttpFoundation\ParameterBag could not be converted to string in /Users/brentlawson23/Sites/laravel4App/app/controllers/TasksController.php line 45","file":"/Users/brentlawson23/Sites/laravel4App/app/controllers/TasksController.php","line":45}}
Yes, I have studied the Symfony API.
I had a similar problem. Input from Backbone is converted to array in Laravel. On tutsplus, Jeffrey Way is using object. So I was trying to do this (like in tutorial):
return $input->title // using object,but got an error.
If I change that line to:
return $input["title"] // everything works fine with array.
I'm also working through the Backbone tutorial on tuts+. If I'm right in assuming are you stuck on the Creating New Contacts section? Below is how I got it to work for me, in ContactController.php:
public function store()
{
$input = Input::all();
Contact::create(array(
'first_name' => $input['first_name'],
'last_name' => $input['last_name'],
'email_address' => $input['email_address'],
'description' => $input['description']
));
}
And then also needed to update app/models/Contact.php with the below:
class Contact extends Eloquent {
protected $fillable = array('first_name', 'last_name', 'email_address', 'description');
}
That should get it working for you and insert the contact into the database. If I've misread let me know and I can have another look.
Cheers,
Sean
In my CakePHP application, I have a model like this:
class Duck extends AppModel {
var $name = 'Duck';
function get_table_name() {
$tbl_name = //compute default table name for this model
}
}
I would like to write the function get_table_name() that outputs the default table name for the model. For the example above, it should output ducks.
EDIT:
Several people have pointed out the use of $this->table.
I did small testing and found out the following:
In the question as I have put above, $this->table indeed contains the table name.
However, actually, my code looked more like this:
class Duck extends Bird {
var $name = 'Duck';
function get_table_name(){
$tbl_name = //comput default table name for this model
}
}
class Bird extends AppModel {
}
In this case $this->table is empty string.
I went with this approach because I wanted to share some code between two of my models. Looks like this is not a good way to share code between models which need some common functionality.
You're looking for the Inflector class.
Inflector::tableize($this->name)
(tableize calls two Inflector methods to generate the table name: underscore() and pluralize())
Edit:
According to the source code, $this->table should contain the name of the table that CakePHP will use for the model, but in my experience this isn't always set. I'm not sure why.
To get the name of the table that the model is currently using, you can use: $this->table. If you don't manually change the model's table conventions, this may be the most useful in the case of CakePHP ever changing its conventions to use table names using something other than Inflector.
CakePHP's Inflector
function get_table_name() {
$tbl_name = Inflector::pluralize($this->name);
}
OR the tableize method
function get_table_name() {
$tbl_name = Inflector::tableize($this->name);
}
Edit
This also addresses the apparent "ghost" issue with $this->table in the Model.
Digging around in the __construct for Model I discovered two things:
Cake uses Inflector::tableize() to get the table name. This alone is enough to warrant using tableize over pluralize. You'll get consistent results.
$this->table is not set by the Model::__construct() unless $this->useTable === false AND $this->table === false.
It appears that if you know you haven't set $this->useTable to false you should be able to use this over $this->table. Admittedly though I only briefly scanned the source and I haven't really dug deep enough to say why $this->table isn't working sometimes.
To get the full table name for a model you have to take the table prefix into account.
$table = empty($this->table) ? Inflector::tableize($this->name) : $this->table;
$fullTableName = $this->tablePrefix . $table;
I used to use inflector to get the table name from model's name
$tableName = Inflector::pluralize(Inflector::underscore($model));
but this is not really universal, using useTable looks better, by default it will contain table's name by convention, and if you have a table that does not match the conventions, then you should manually specify it by useTable. So, in both cases the result will be correct
$this->User->useTable