I am using Yajra Datatables for Service for my Laravel project and wonder if i can use Carbon to change date format.
My datatables currently displaying date as bellow format
2020-11-11T16:03:13.000000Z
I want to display my date as
11-11-2020 03:13 PM
How can i do that. Please help.
My Datatables:
<?php
namespace App\DataTables;
// use App\App\OrderDataTable;
// use OrderDataTable;
use App\DataTables\OrderDataTable;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
use App\Order;
use Illuminate\Support\Facades\DB;
class OrderDataTable extends DataTable
{
public function dataTable($query){
return datatables()
->eloquent($query);
}
public function query(OrderDataTable $model){
$from = date('2020-11-10 00:00:00');
$to = date('2020-11-11 23:59:59');
// $data = Order::where('created_at', '2020-11-11 22:03:13');
// $data = Order::select();
$data = Order::query()
// ->whereBetween('created_at', ['2020-11-10 00:00:00', '2020-11-11 23:59:59'])
->whereBetween('created_at', [$from, $to])
->select([
'orders.id',
'orders.ecomordid',
'orders.status_id',
'orders.awb',
'orders.created_at'
]);
return $this->applyScopes($data);
}
public function html(){
return $this->builder()
->setTableId('orderdatatable-table')
// ->columns($this->getColumns())
->columns([
'id' => [ 'title' => 'SHIPPING CODE' ],
'ecomordid' => [ 'title' => 'ECOM ORDER' ],
'status_id' => [ 'title' => 'STATUS' ],
'awb' => [ 'title' => 'AWB' ],
'created_at' => [ 'title' => 'DATE' ],
])
->minifiedAjax()
->dom('Bfrtip')
->orderBy(0)
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['excel', 'print', 'reset', 'reload'],
'initComplete' => "function () {
this.api().columns([0,3]).every(function () {
var column = this;
var input = document.createElement(\"input\");
$(input).appendTo($(column.footer()).empty())
.on('change', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}",
]);
}
protected function getColumns(){
return [
Column::make('id'),
Column::make('ecomordid'),
Column::make('status_id'),
Column::make('awb'),
Column::make('created_at'),
];
}
protected function filename(){
return 'Order_' . date('YmdHis');
}
}
View:
#extends('layouts.master')
#section('content')
<meta name="csrf-token" content="{{ csrf_token() }}" />
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header bg-orange"><h3>{{ __('Update By AWB') }}</h3></div>
<div class="card-body">
<div class="table-responsive">
<div class="panel panel-default">
<div class="panel-heading">Sample Data</div>
<div class="panel-body">
{!! $dataTable->table([], true) !!}
{!! $dataTable->scripts() !!}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
Controller
public function order(OrderDataTable $dataTable){
// dd($dataTable->request()->all());
return $dataTable->render('admin.search.order');
}
My current output
I am using:
Laravel: 7.28.4
laravel-datatables-buttons: 4.0
laravel-datatables-html: 4.0
laravel-datatables-oracle: 9.14
You can define an Accessor in Order model
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d H:i:s');
}
Note that it will work globally wherever you access created_at field it will be fetched with this format.
Read more about Accessors Here
Related
LONG POST WARNING
why isn't my form to create a new user not working? im using laravel 9 and livewire. This is my code:
this is the button from where i show the model to create a form:
<div class="py-4 space-y-4">
<div class="flex justify-between px-2">
<div class="w-1/4">
<x-jet-input placeholder="search will go here"/>
</div>
<div>
<x-jet-button wire:click="create">New Skill</x-jet-button>
</div>
</div>
</div>
This is the model that shows the form. this model is also used to edit a skill as per Caleb the livewire creator:
<form wire:submit.prevent="save">
<x-jet-dialog-modal wire:model.defer="showEditModal">
<x-slot name="title">Edit Skill</x-slot>
<x-slot name="content">
<div class="col-span-6 sm:col-span-4">
<x-jet-label for="name" value="{{ __('Skill name') }}" />
<select wire:model="editing.name"
id="name"
type="text"
class="mt-1 block w-full border-gray-300
focus:border-indigo-300 focus:ring
focus:ring-indigo-200 focus:ring-opacity-50
rounded-md shadow-sm">
#foreach(\App\Models\Skill::LANGUAGES as $value => $label)
<option value="{{ $value }}">{{ $label }}</option>
#endforeach
</select>
<x-jet-input-error for="editing.name" class="mt-2" />
<x-jet-label for="years" value="{{ __('Years of experience') }}" class="mt-4"/>
<x-jet-input wire:model="editing.years" id="years" type="number"
min="{{\App\Models\Skill::MIN_YEARS_OF_EXPERIENCE}}"
max="{{\App\Models\Skill::MAX_YEARS_OF_EXPERIENCE}}"
class="mt-1 block w-full"
placeholder="Years of experience"/>
<x-jet-input-error for="editing.years" class="mt-2" />
</div>
</x-slot>
<x-slot name="footer">
<x-jet-secondary-button wire:click="$set('showEditModal', false)" class="mr-2">Cancel</x-jet-secondary-button>
<x-jet-button type="submit">Save</x-jet-button>
</x-slot>
</x-jet-dialog-modal>
</form>
And this is my livewire component:
<?php
namespace App\Http\Livewire;
use App\Models\Skill;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class Skills extends Component
{
public $name ='';
public $showEditModal = false;
public Skill $editing;
public function rules()
{
return [
'editing.name' => 'required|in:'.collect(Skill::LANGUAGES)->keys()->implode(','),
'editing.years' => 'required|numeric|between:' . Skill::MIN_YEARS_OF_EXPERIENCE . ',' . Skill::MAX_YEARS_OF_EXPERIENCE,
];
}
public function render()
{
return view('livewire.skills', [
'skills' => Skill::where('user_id', auth()->id())->get(),
]);
}
public function mount(){
$this->editing = $this->makeBlankSkill();
}
public function makeBlankSkill(){
return Skill::make([
'name' => 'javascript',
'user_id' => auth()->user()->id,
]);
}
public function create(){
if ($this->editing->getKey()) $this->editing = $this->makeBlankSkill();
$this->showEditModal = true;
}
public function edit(Skill $skill) {
if ($this->editing->isNot($skill)) $this->editing = $skill;
$this->showEditModal = true;
}
public function save()
{
$this->validate();
$this->editing->save();
$this->showEditModal = false;
}
}
I keep getting SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value and i dont know why.
This is my modal:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Skill extends Model
{
use HasFactory;
const DEFAULT_OPTION = 'Please select a skill';
const LANGUAGES = [
'javascript' => 'JavaScript',
'php' => 'PHP',
'python' => 'Python',
'java' => 'Java',
'c#' => 'C#',
'c++' => 'C++',
'ruby' => 'Ruby',
'swift' => 'Swift',
'typescript' => 'TypeScript',
'rust' => 'Rust',
'go' => 'Go',
'kotlin' => 'Kotlin',
'scala' => 'Scala',
'dart' => 'Dart',
'r' => 'R',
'perl' => 'Perl',
'elixir' => 'Elixir',
'clojure' => 'Clojure',
'haskell' => 'Haskell',
'erlang' => 'Erlang',
'lisp' => 'Lisp',
'sql' => 'SQL',
'bash' => 'Bash',
'laravel' => 'Laravel',
'symfony' => 'Symfony',
'codeigniter' => 'CodeIgniter',
'yii' => 'Yii',
'zend' => 'Zend',
'cakephp' => 'CakePHP',
'fuelphp' => 'FuelPHP',
'slim' => 'Slim',
'lumen' => 'Lumen',
'phalcon' => 'Phalcon',
'silex' => 'Silex',
'express' => 'Express',
'koa' => 'Koa',
'hapi' => 'Hapi',
'meteor' => 'Meteor',
'angular' => 'Angular',
'ember' => 'Ember',
'react' => 'React',
'vue' => 'Vue',
'backbone' => 'Backbone',
'd3' => 'D3',
'threejs' => 'Three.js',
];
const MIN_YEARS_OF_EXPERIENCE = 1;
const MAX_YEARS_OF_EXPERIENCE = 50;
protected $fillable = [
'name', 'user_id', 'years'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
Any help is greatly appriceated
I've done all there is to do.At least i hope. I've added the
$illable
array ive set the
'user_id' => auth()->user()->id,
Not sure what else im missing
public function save()
{
$this->validate();
$user = auth()->user();
$this->editing->user_id = $user->id;
$this->editing->save();
$this->showEditModal = false;
}
This was the answer for me
If user_id is null when creating a new Skill, this means there is no authenticated user. You can simply check by doing dd(auth()->id()). If you're logged in, this will return the primary key for your authentication model. If this is empty, you're simply not authenticated, and so you must first log in.
In the case your user_id is actually set, but it isn't arriving in your database upon saving, you'll have to check if the property user_id is correctly set on the Skill model's protected $fillable property.
If you dd($this->editing) right after mount, you can check the attributes of the model, and if the user_id is set, you know the error happens when saving to the database.
As it turns out, Livewire won't hydrate newly set properties on models. This is because Livewire "rehydrates" the models by simply re-fetching them from the database. This can be solved defining a rules property as shown here, directly relating to the model properties. This would ensure Livewire keeps the state of the updated properties.
So I am working on a laravel project and I want that if a user types in their order code, the order will show up with the details. For some reason, the order code doesn't get through the if statement, because I get the output 'Order not found.' all the time, even if I type in an order code that is present in my orders table.
TrackController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order;
class TrackController extends Controller
{
public function index()
{
return view ('track.index');
}
public function show($id)
{
$order = Order::where('code', $id)->first();
return view('track.show',[
'order' => $order
]);
}
public function redirect(Request $request)
{
$orderCode = $request->input('order-track-id');
$order = Order::where('code', $orderCode)->first();
if(!$order){
return redirect('/track')->with('error', 'Order not found.');
}else{
return redirect('/track/' . $order->code);
}
}
}
web.php
Route::get('/track', 'TrackController#index');
Route::post('/track/redirect', 'TrackController#redirect');
Route::get('/track/{id}', 'TrackController#show');
track.index
#extends('layouts/app')
#section('content')
<div class="container">
<div class="row justify-content center">
{!! Form::open(['action' => 'TrackController#redirect', 'method' => 'post']) !!}
{!! csrf_field() !!}
<input type="number" name="input-order-track-id" id="order-track-id">
{{ Form::button('Track', ['type' => 'submit', 'class' => 'btn btn-primary'] ) }}
{!! Form::close() !!}
</div>
</div>
#endsection
What am I doing wrong and why isn't my function putting me through to the show function in the TrackController?
In your redirect controller function.
public function redirect(Request $request)
{
$orderCode = $request->input('input-order-track-id');
$orders = Order::where('code', $orderCode)->get();
if($orders->isEmpty()){
return redirect('/track')->with('error', 'Order not found.');
}else{
$order = Order::where('code', $orderCode)->first();
return redirect('/track/' . $order->code);
}
}
i want to add button in Yajra, so i read http://dt54.yajrabox.com/buttons/eloquent.
Im following the step. But still show blank.
nb. if im not using datatable service running well.
Datatables class
namespace App\DataTables;
use App\employee;
use Yajra\Datatables\Services\DataTable;
class EmployeeDataTable extends DataTable
{
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->make(true);
}
public function query()
{
$query = employee::select();
return $this->applyScopes($query);
}
public function html()
{
return $this->builder()
->columns($this->getColumns())
->ajax('{{ url("Employee/index3") }}')
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['export', 'print', 'reset', 'reload'],
]);
}
protected function filename()
{
return 'employeedatatables_' . time();
}
in Controller
use Yajra\Datatables\Facades\Datatables;
use App\DataTables\EmployeeDataTable;
public function index3(EmployeeDataTable $dataTable)
{
return $dataTable->render('employee.users');
}
in View
#extends('layouts.app')
#section('content')
<div class="col-md-8 col-md-offset-2">
<h3>test</h3>
{!! $dataTable->table() !!}
</div>
{!! $dataTable->scripts() !!}
#endsection
If i used firebug, i've got error 304 not modified.
Can you tell me what my mistake,pls ?
Solved.. maybe can help somebody..
this is Column search,and add action using Datatabale service
in Datatables class
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->addColumn('action', function ($query) {
return '<i class="glyphicon glyphicon-edit"></i> Edit
<i class="glyphicon glyphicon-minus-sign"></i> Del';
})
->make(true);
}
public function query()
{
$query = employee::select('ID','cNip','vName','vBankbranch');
return $this->applyScopes($query);
}
public function html()
{
return $this->builder()
->columns($this->getColumns())
->addAction(['width' => '10%'])
->ajax('')
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['export', 'print', 'reset', 'reload'],
'initComplete' => "function () {
this.api().columns().every(function () {
var column = this;
var input = document.createElement(\"input\");
$(input).appendTo($(column.footer()).empty())
.on('change', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}",
]);
}
in View
#extends('layouts.app')
#section('content')
<div class="col-md-8 col-md-offset-2">
<h3>test</h3>
{!! $dataTable->table([], true) !!}
</div>
#endsection
#section('scripts')
{!! $dataTable->scripts() !!}
#endsection
I'm trying to use conditional validation on a attribute account_no. It should be validate only when I select the value 'old' in the attribute account_version. But it is not working. The error I'm getting is validation is required for newalso. Should I use javascript instead to validate
My code in model
return [
['account_no', 'required', 'when' => function($model) {
return $model->account_version == 'Old';
}],
]
My code in form
<?php if ($model->isNewRecord) {?>
<div class="row">
<div class="col-md-2">
<label for="">Account Version</label>
</div>
<div class="col-md-2">
<?php echo $form->field($model, 'account_version')->radioList(['New'=>'New','Old'=>'Old'])->label(false); ?>
</div>
<div id="action_block" class="col-md-6">
<div class="col-md-3">
<label for="">Account No:</label>
</div>
<div class="col-md-3">
<?= $form->field($model, 'account_no')->textInput(['maxlength' => true])->label(false) ?>
</div>
</div>
</div>
<?php } ?>
Model
[['account_no'], 'required', 'when' => function ($model) { return $model->account_version == 'Old'; }, 'whenClient' => "function (attribute, value) { return $('#modelName[account_version]').val() == 'Old'; }"],
Form
<?php $form = ActiveForm::begin(['id' => 'account-form', 'enableAjaxValidation' => true]); ?>
Controller
if($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return yii\widgets\ActiveForm::validate($model);
}
}
<?php
return [
['account_no', 'required', 'when' => function ($model) {
return $model->account_no == 'Old';
}, 'whenClient' => "function (attribute, value) {
return $('#account_no').val() == 'Old';
}"]
]
?>
http://www.yiiframework.com/doc-2.0/guide-input-validation.html [reference links]
Still noob and learning Laravel, I am currently in the middle of a simple validation with FormRequest. What I am facing today is the edit of an existing entry.
I have written in my FormRequest that I want the name to be unique. It works perfectly but of course when I edit an existing entry, I cannot save it anymore, it already exists... of course it does since I am editing it.
I found the solution reading the documentation, but unfortunately, it does not work. Here's my code:
Routes:
Route::resource('editeurs', 'PublishersController');
Controller:
class PublishersController extends Controller
{
/* Update an existing publisher */
public function update($slug, PublisherRequest $request)
{
$publisher = Publisher::where('slug', $slug)->firstOrFail();
$input = $request->all();
$publisher->name = $input['name'];
$publisher->slug = my_slug($input['name']);
$publisher->save();
return redirect()->action('PublishersController#show', $publisher->slug);
}
}
FormRequest:
class PublisherRequest extends Request
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|unique:publishers,name,'.?????
];
}
}
If needed, the view:
#section('content')
<div class="row">
<h1 class="large-12 columns">Edition - {!! $publisher->name !!}</h1>
{!! Form::model($publisher, ['method' => 'PATCH', 'action' => ['PublishersController#update', $publisher->slug]]) !!}
<div class="large-12 columns">
{!! Form::label('name', 'Nom de l\'éditeur') !!}
{!! Form::text('name', null, ['placeholder' => 'Nom de l\'éditeur']) !!}
</div>
<div class="large-12 columns">
{!! Form::submit('Ajouter un éditeur', ['class' => 'button expand']) !!}
</div>
{!! Form::close() !!}
</div>
#stop
What is wrong with my code?
Here is how I would do it:
class PublishersController extends Controller
{
/* Update an existing publisher */
public function update($slug, PublisherRequest $request)
{
$publisher = Publisher::where('slug', $slug)->firstOrFail();
$this->validate($request, ['name' =>'required|unique:publishers,name,'.$publisher->id]);
$publisher->name = $request->input('name');
$publisher->slug = my_slug($publisher->name);
$publisher->save();
return redirect()->action('PublishersController#show', $publisher->slug);
}
}
OK, I found the solution. I needed to pass the slug of my current publisher.
public function rules()
{
$publisher = Publisher::where('slug', $this->editeurs)->first();
return [
'name' => 'required|unique:publishers,name,'.$publisher->id
];
}
This works.