I am making a API request but when i retrieve created_at then i get 2019-10-09T11:07:08.000000Z but in database it is 2019-10-09 11:07:08. How can i solve this issue? I don't want to use date formatting because i already have proper date format in my database. I just want what i have in database. Look at my database: https://prnt.sc/piljms
API Controller:
public function singleGallery($id)
{
$gallery = Gallery::findOrFail($id);
return new GalleryResource($gallery);
}
Gallery Resource:
return [
'gallery_id' => $this->id,
'created_date' => $this->created_at,
'modified_date' => $this->updated_at
]
Using php's date and strtotime function you can format date as per your choice.
'created_date' => date('Y-m-d', strtotime($this->created_at))
I have formatted created_at in Year/month/date but you can do different formatting like d/m/Y for day/month/Year
If you would like to go Laravel way then you have to use Carbon library.
Go with this:
return [
'gallery_id' => $this->id,
'created_date' => $this->created_at->format('Y-m-d H:i:s'),
'modified_date' => $this->updated_at->format('Y-m-d H:i:s'),
]
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;
class Notification extends Model
{
use HasFactory;
protected $fillable = [
'id',
'created_at',
'updated_at',
];
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
}
?>
Related
I am filling a database with seeders and factory, the problem is that I need to fill the CREATED_AT field with dates that are not today's date but random, to be able to fill the different graphs that the page has.
I tried and sometimes it inserts data and other times it throws error that the field is invalid and that is in date format the error that throws me in the console.
ERROR MESSAGE
"Incorrect datetime value: '2021-09-05 00:00:00' for column 'created_at' at row 1"
Error image
CODE
$factory->define(Opportunity::class, function (Faker $faker) {
$account_id = Account::all()->random()->id;
$account = Account::find($account_id);
$contact = Contact::where('account_id',$account_id)->inRandomOrder()->limit(1)->first();
$created = $this->faker->dateTimeBetween($startDate = '-3 month', $endDate = 'now +6 month');
$date = strtotime('+2 days', strtotime(Carbon::parse($created)));
return [
'created_at' => Carbon::parse($created)->format('Y-m-d H:i:s'), ///line error
'name' => $this->faker->name .' '.$this->faker->sentence(2),
'amount' => $this->faker->numberBetween($min = 120000, $max = 20000000),
'probability' => $faker->randomElement(['0','10','20','30','40','50','60','70','80','90','100']),
'description' => $this->faker->paragraph,
'lead_source_id'=> LeadSource::all()->random()->id,
'sales_stage_id'=> 1,
'account_id' => $account_id,
'user_id' => $account->user_id,
'contact_id' => ( $contact != null ? $contact->id : null),
'close_date' => Carbon::parse($date)->format('Y-m-d'),
'product_line_id'=> ProductLine::all()->random()->id
];
});
Try by changing $this->faker to $faker and migration should have $table->timestamps();
then u can use dateTimeBetween directly like this
'created_at'=>$faker->dateTimeBetween($startDate = '-3 month',$endDate = 'now +6 month')
OpportunitySeeder Class
public function run()
{
factory(App\Opportunity::class,5)->create();
}
DatabaseSeeder class
$this->call([
OpportunitySeeder::class
]);
https://laravel.com/docs/6.x/database-testing#using-seeds
Hello guys please I'm having this laravel error in my controller and I need help
Here's my controller
public function expectingpost(Request $request)
{
DB::table('expectings') ->insert([
$validatedData = $request->validate([
"time" => 'required|date_format:H:i',
"day" => 'required|date_format:Y-m-d',
"name" => 'required'
]).
"time" => $request->time,
"day" => $request->date,
"name" => $request->name
]);
return back() -> with('expecting', $request->input('name') . ' has been added as your guest');
}
}
PLease guys I seriously need fast responses because this has kept me on deck for long. Thank you
You shouldn't validate your data inside your insert, this should be first validating your data, then use it to create your model. Another improvement use Eloquent models, there is no reason not to if you are just starting out.
public function expectingpost(Request $request)
{
$validatedData = $request->validate([
'time' => 'required|date_format:H:i',
'day' => 'required|date_format:Y-m-d',
'name' => 'required'
]).
Expecting::create($validatedData);
return back()->with('expecting', $validatedData['name'] . ' has been added as your guest');
}
The Eloquent Model you need.
use Illuminate\Database\Eloquent\Model;
class Expecting extends Model {
protected $fillable = ['time', 'day', 'name'];
}
I am trying to update date_of birth column in database and when I submit my form I get this error
DateTime::__construct(): Failed to parse time string (25/03/1995) at position 0 (2): Unexpected character
Now in my blade I formated date of birth to show d/m/Y and when updating I think it updates Y/m/d, because when I remove format function from my blade it works fine. So I need help on how to update with format('d/m/Y') in my database and how to validate it properly in my form request validation. Any help is appreciated. Here is my code.
index.blade.php
<input type="text" placeholder="dd/mm/yyyy" name="date_of_birth" value="{{ $userForShowProfile->date_of_birth ? $userForShowProfile->date_of_birth->format('d/m/Y') : "" }}">
UserController.php
public function updateProfileCharacteristics(UpdateProfileCharacteristicsRequest $request)
{
$user = Auth::user();
$user->update(
[
'date_of_birth' => $request->date_of_birth,
'age' => Carbon::now()->diffInYears($request->date_of_birth),
'updated_at' => Carbon::now()
]
);
return redirect()->route('profile.show', [$user->username]);
}
UpdateProfileCharacteristicsRequest.php
public function rules()
{
return [
'date_of_birth' => ['date'],
];
}
Since you are sending the date in a custom format in the request, you will need to parse it to a format that matches the one in the database column before inserting it:
$user->update(
[
'date_of_birth' => Carbon::createFromFormat("d/m/Y", $request->date_of_birth)->format('Y-m-d'), // parse the right format here
'age' => Carbon::now()->diffInYears(Carbon::createFromFormat("d/m/Y", $request->date_of_birth)),
'updated_at' => Carbon::now()
]
);
And for that date format to pass validation you can use the date_format:format rule instead of date:
public function rules()
{
return [
'date_of_birth' => ['date_format:"d/m/Y"'],
];
}
What is the column type in you database migration? If it is check if it DATE or DATETIME or TIMESTAMP, It is supposed to be DATE hence you can format your date to be Y-m-d.
If you are to save a DATE to DB it should be in the format of Y-m-d.
so try this:
public function updateProfileCharacteristics(Request $request)
{
$user = Auth::user();
$user->update([
'date_of_birth' => Date('Y-m-d',strtotime($request->date_of_birth)),
'age' => Carbon::now()->diffInYears($request->date_of_birth),
'updated_at' => Carbon::now()
]);
return redirect()->route('profile.show', [$user->username]);
}
Am writing an endpoint with Laravel using using. When I tested on postman using POST Method, I got this error:
ErrorException: Trying to get property 'id' of non-object in file C:\xampp\htdocs\testing-file\testing\app\Http\Controllers\ApiController.php on line 912
Controller
public function storeBilling(Request $request)
{
// $billing = Billing::create($request->all());
// return response()->json(['success' => $billing], $this-> successStatus);
$validator = Validator::make($request->all(), [
'network' => 'required'
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
// Creating a record in a different way
$createBilling = Billing::create([
'user_id' => $request->user()->id,
'network' => $request->network,
'sender' => $request->sender,
'recipient' => $request->recipient,
'message' => $request->message,
'amount' => $request->amount,
'billing_type' => $request->billing_type,
]);
return new BillingResource($createBilling);
}
Model
class Billing extends Model
{
protected $table = 'billing';
protected $fillable = [
'network' ,
'sender',
'recipient',
'message',
'timestamp',
'created_at',
'updated_at',
'amount',
'billing_type',
'user_id',
'service_name',
'package',
'email',
'user_id'
];
public function user() {
return $this->belongsTo('App\User');
}
}
Resource
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Billing;
class BillingResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'network' => $this->network,
'sender' => $this->sender,
'recipient' => $this->recipient,
'message' => $this->message,
'amount' => $this->amount,
'billing_type' => $this->billing_type,
'email' => $this->email,
'user' => $this->user,
'service' => $this->service,
'package' => $this->package,
// Casting objects to string, to avoid receive create_at and update_at as object
'timestamp' => (string) $this->timestamp,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at
];
}
}
If I use this POST Method:
http://localhost/testing-file/stesting/api/storeBilling?network=100
It suppose to post into the database, but I got this error:
ErrorException: Trying to get property 'id' of non-object in file C:\xampp\htdocs\testing-file\testing\app\Http\Controllers\ApiController.php on line 912
'user_id' => $request->user()->id
Your error is saying that $request->user() is not an object, so you cannot access its parameters using object notation, e.g. ->id.
If you dd($request->user) you may see that you are not getting what you thought you were getting - it may be an array, or it may not be the right value at all.
If it is an array, you can access the value like $request['user']['id']. It really depends what you are passing in your POST request.
$request->user()->id is incorrect.
If you want the current user you can use Auth::user().
In the beginning of your question you said you are trying to build an endpoint using Lravel ..
Postman will not have access to the user object unless authenticated, if authenticated then this should work ::
$request->user()->id or Auth::user()->id or $request["user"]["id"]
on you
public function storeBilling(Request $request)
You write $createBilling = Billing::create([
'user_id' => $request->user()->id, and this create error.
Or is preferable to have $createBilling = Billing::create([
'user_id' => Auth::user()->id, to find the id of the user authentificate.
don't forget to add use Auth; at the beginning of the controller
Going through a same Hassle it's happening because relationship finding its relation with billing table but it did not find so giving this error please check your database have related entry's and try again and make sure you have right relationship with table.
I have a StartDate field and a EndDate field. Both may start today or in the future. It is possible to have them both start on the same day, including today.
I have to make a validation for these.
What I've done so far is this:
'StartDate'=>'required|date_format:Y/m/d|after:yesterday',
'EndDate' => 'date_format:Y/m/d|after:yesterday',
What I don't know how to do is to validate true if both dates are equal as a second condition.
Anyone can help me, please ?
This is how you can validate date:
'start_date' => 'required|date',
'end_date' => 'required|date|after_or_equal:start_date'
EDIT
This was a solution up to Laravel 5.3. With Laravel 5.4, a rule after_or_equal was introduced
https://laravel.com/docs/5.4/validation#rule-after-or-equal
I had the same need for my web app. I solved it by creating a custom Request with the following rules method :
public function rules()
{
$rules = [
'start_date' => 'date_format:Y-m-d|after:today'
];
if ($this->request->has('start_date') && $this->request->get('start_date') != $this->request->get('end_date')) {
$rules['end_date'] = 'date_format:Y-m-d|after:start_date';
} else {
$rules['end_date'] = 'date_format:Y-m-d|after:today';
}
return $rules;
}
As per my understand I try to prepare custom validation rule which could help you to meet your requirement.
Current below mentioned rule only check if a start date is before end date.
<?php
namespace App\Providers;
use Validator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider{
public function boot(){
Validator::extend('date_after', function($attribute, $value, $parameters) {
return strtotime( $value ) > strtotime( $this->attributes[ $parameters[0] ] );
});
Validator::extend('date_equal', function($attribute, $value, $parameters) {
return strtotime( $value ) == strtotime( $this->attributes[ $parameters[0] ] );
});
}
}
?>
Usage:
<?php
$inputs = array(
'start_date' => '2013-01-20',
'end_date' => '2013-01-15'
);
$rules = array(
'start_date' => 'required',
'end_date' => 'required|date_after:start_date'
);
$messages = array(
'date_after' => ":attribute must be date after Start Date."
);
$validation = Validator::make($inputs, $rules, $messages);
if( $validation->fails() )
{
echo '<pre>';
print_r($validation->errors);
echo '</pre>';
}
?>
However I did not test that code with my env... but I believe its help you much to meet requirement.
Please let me know your further requirement so I can provide specifically solution to your requirement.