Laravel schema builder, update nullable timestamp field - php

I am developing a project where I have to store information of a job. For example job_start_date,job_end_date,payment_received_date. It will be nullable initially. As soon as the job starts admin will update job_start_date and job_end_date column. So I cannot set current date and time as default to those field. The problem is, while updating the job_start_date field, if laravel finds that the job_start_date column is null, it throws an error. Call to a member function format() on a non-object. Even though I have declared protected $dates = ['job_start_date','job_end_date','payment_received_date']; in my model. Any suggestion to overcome this problem?
example code:
<!-- job start date -->
<div class="form-group {{ $errors->has('job_start_date') ? 'has-error' : '' }}">
<label class="col-md-4 control-label" for="job_start_date">Job Start Date</label>
<div class="col-md-4">
<input id="job_start_date" name="job_start_date" type="date" value="{{ $job_account_detail->job_start_date->format('Y-m-d') }}" class="form-control input-md">
{!! $errors->first('job_start_date','<span class="help-block">:message</span>') !!}
</div>
</div>

You can check for null value in your view to avoid the error
<input id="job_start_date" name="job_start_date" type="date" value="{{ !is_null($job_account_detail->job_start_date) ? $job_account_detail->job_start_date->format('Y-m-d') : "" }}" class="form-control input-md">
I would add a method in the model to handle validation and formatting to make my life easier:
// in your model
public function getJobStartDateInDateStringFormat() {
return !is_null($this->job_start_date)
? $this->job_start_date->format("Y-m-d")
: "";
}
Then in your view you can just call the method:
<input id="job_start_date" name="job_start_date" type="date" value="{{ $job_account_detail->getJobStartDateInDateStringFormat() }}" class="form-control input-md">

Related

old() value function using data from database not working in Blade

I have a form with 4 input fields, all of them to which I applied an old() function so whenever users load the page after submitting the form, the data that they filled in would retain in the fields for better UX.
My issue is that out of these 4 fields, only 1 has the old() function working. The difference between this field and the others is that:
The name and id attributes for this field are the same, while other fields have different names and IDs respectively.
The input type for this field is type="number" while the other fields are type="text".
Based on these differences, I tried modifying the code to standardize them, and only one solution works which is that I change the input types to "number", however, not all my inputs are numbers, so it is not an ideal solution.
Form blade file:
<div class="form-group mb-3">
<input type="text" class="form-control" name="emp_name" id="company_name"
value="{{ old('emp_name' , (isset($user->emp_detail->emp_name) ? $user->emp_detail->emp_name : old('emp_name')) ) }}">
#if ($errors->has('emp_name'))
<span class="text-danger">{{ $errors->first('emp_name') }}</span>
#endif
</div>
<div class="form-group mb-3">
<input type="number" class="form-control" name="emp_length" id="emp_length"
value="{{ old('emp_length' , (isset($user->emp_detail->emp_length) ? $user->emp_detail->emp_length : old('emp_length')) ) }}">
#if ($errors->has('emp_length'))
<span class="text-danger">{{ $errors->first('emp_length') }}</span>
#endif
</div>
<div class="form-group mb-3">
<input type="text" class="form-control money-prefix" name="emp_monthly_gross_salary" id="monthly_salary"
value="{{ old('emp_monthly_gross_salary' , (isset($user->emp_detail->emp_monthly_gross_salary) ? $user->emp_detail->emp_monthly_gross_salary : old('emp_monthly_gross_salary')) ) }}">
#if ($errors->has('emp_monthly_gross_salary'))
<span class="text-danger">{{ $errors->first('emp_monthly_gross_salary') }}</span>
#endif
</div>
<div class="form-group mb-3">
<input type="text" class="form-control money-prefix" name="monthly_allowance" id="bonus"
value="{{ old('monthly_allowance' , (isset($user->emp_detail->emp_monthly_allowance) ? $user->emp_detail->emp_monthly_allowance : old('monthly_allowance')) ) }}">
#if ($errors->has('monthly_allowance'))
<span class="text-danger">{{ $errors->first('monthly_allowance') }}</span>
#endif
</div>
To be clear, I also have several other forms in which I applied the same old() function, with texts as well as numbers, and they work fine, so I am unsure why the old() function won't work on this form specifically. I also dd() the variables I wanted to output as the old function, so I am sure my controller is already passing the values, my blade just isn't showing it.
Can anyone advise me on this problem?
maybe the issue is the default value, may be set but empty
try to check it with old directly without the default value
ex:
replace
{{ old('emp_name' , (isset($user->emp_detail->emp_name) ? $user->emp_detail->emp_name : old('emp_name')) ) }}
with
{{ old('emp_name') }}
if it works fine with you then you need to enhance the default value condition
ie: (isset($user->emp_detail->emp_name) ? $user->emp_detail->emp_name : old('emp_name')

how to display old datetime-local value in laravel?

how to display old datetime-local value in laravel ? in database i have datetime data with format 2021-09-29 14:07:00, and now i want to show datetime data when open edit page.
I've tried displaying datetime data with code like below, but still not working.
<div class="form-group">
<label for="datetime">Datetime</label>
<input type="datetime-local" name="datetime" class="form-control #error('datetime') is-invalid #enderror" id="datetime" value="{{old('datetime') ? old('datetime') : Carbon\Carbon::parse($data->datetime)->isoFormat('MM/DD/YYYY hh:mm A')}}">
#error('datetime')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
what is the correct way to display it? thx

laravel update registered user

I have recently started working in Laravel, my first Framework. I have experience with PHP but I am a little lost now.
I used the default auth that comes with laravel. But I am trying to make a function to edit the users that have registered.
I dont quite see how the data gets to the database from the form.
My form: (didn't put all inputs)
#isset($user)
<form method="POST" action="{{ WHAT GOES HERE?? }}">
#csrf
{{--name--}}
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ $user->name }}" required autofocus>
</div>
</div>
{--last name--}}
<div class="form-group row">
<label for="lastname"
class="col-md-4 col-form-label text-md-right">{{ __('Last Name') }}</label>
<div class="col-md-6">
<input id="lastname" type="text"
class="form-control{{ $errors->has('lastname') ? ' is-invalid' : '' }}" name="lastname" value="{{ $user->lastname }}" required autofocus>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Edit user') }}
</button>
</div>
</div>
I did not make a route yet, as I do not know how exactly. Or if this is even needed.
My controller:
public function edit_profile($userId, Request $request)
{
$this->isAllowed($userId, true);
$userProfile = User::findOrFail((int)$userId);
//TODO validation
//TODO update user model + save to db
$userProfile->update();
return view('user/edit_profile', [
/* $ */
'user' => $userProfile,
]);
}
As stated; I do know what needs to happen. I just don't know and understand how.
And last, my user.php
protected $fillable = [
'name',
'lastname',
'email',
'password',
'mobile_number',
'date_of_birth',
];
My next step would be to make a route, to get the data to the controller. But I don't see how this route would look.
You need to create a Route for your action.
Go to routes->web.php(laravel 5.3 or above) and add your route structure.
Route::http-verb('url name',"Controller name#Controller Method name");
This is the route you have to add in your web.php file
Route::post('edit-profile', 'ProfileController#edit_profile');
I am assuming that you have a controller with name as ProfileController and inside you have edit_profile method.
{{ url('/edit-profile') }}
add above code to action attribute.
If you are using laravel 5.2 or old version the routes configuration resides inside app/Http/routes.php.

Merge create and edit blade files to 1 file?

I have created a create form create.blade.php and a edit form edit.blade.php - both form fields are identical.
It quite annoying when I add new fields in the create.blade.php, I also need to add fields in edit.blade.php.
How can I merge into 1 blade file it so it work for both way for creating and editing (view via db).
For example in create.blade.php I have this:
<label>Name</label>
<input type="text" name="name" value="{{ old('name') }}">
#if ($errors->has('name'))
<label class="error">{{ $errors->first('name') }}</label>
#endif
In edit.blade.php
<label>Name</label>
<input type="text" name="name" value="{{ old('name', $category->name) }}">
#if ($errors->has('name'))
<label class="error">{{ $errors->first('name') }}</label>
#endif
Just check if model exists:
{{ old('name', empty($category) ? '' : $category->name) }}
Also, you may want to check if it's create or update form and change form url accordingly:
{{ route(empty($category) ? 'article.create' : 'article.update' ) }}
<input type="text" name="name" value="{{ $category ? $category->name : old('name') }}">
you can use a partial (fancy name for a smaller template) for your form, and pass that partial the data you require.
Using the example of a booking system:
In your create blade file:
#include('bookings._forms', ['booking' => new \App\Booking])
and the edit file ($booking being retrieved on the controller):
#include('bookings._forms', ['booking' => $booking])
And then your form partial can look like this:
<label for="name" class="label">Name</label>
<input type="text"
class="input"
name="name" id="name"
placeholder="Guest name"
value="{{ old('name') ?? $booking->name }}">
The good thing with this method is that now you can have ONLY your form elements on the partial and only have to update 1 file when you add fields, AND the actual tag stays on your create and edit template, so no worries about that either.
Hope that's clear and it helps.

Laravel 5.3 Eloquent - How to post data to multiple tables with a form?

So far I can only post data to 1 table with a form.
My controller:
public function store(Request $request, Role $role)
{
$role->fill($request->all());
$role->save();
return redirect('/roles');
}
My view:
<div class="form-group">
<label for="name-input">#lang('role.name')</label>
<input id="name-input" type="text" name="name" class="form-control" value="{{ isset($role) ? $role->name : '' }}" autofocus>
</div>
<div class="form-group">
<label for="description-input">#lang('role.description_optional')</label>
<textarea id="description-input" name="description" class="form-control">{{ isset($role) ? $role->description : '' }}</textarea>
</div>
So it perfectly stores the name and description, but what if I wanted to store data to a second table?
Something like this
$second = new SecondTableModel();
$second->fill($request->all());
$second->save();

Categories