I'm trying to bind a date field (mydate) with laravel livewire. Basically I did the following:
In the model, I did a cast and created a mutator and an accessor:
<?php
namespace App\Models\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Platform extends Model
{
use HasFactory;
protected $fillable = ['name', 'mydate'];
protected $dates = ['created_at', 'updated_at', 'mydate'];
protected $casts = ['mydate' => 'datetime'];
public function getCreatedAtBrAttribute()
{
return optional($this->created_at)->format('d/m/Y H:i');
}
public function getUpdatedAtBrAttribute()
{
return optional($this->updated_at)->format('d/m/Y H:i');
}
public function getMydateBrAttribute()
{
return optional($this->mydate)->format('Y-m-d\TH:i');
}
public function setMydateBrAttribute($value)
{
$this->mydate = Carbon::parse($value)->format('Y-m-d H:i:s');
}
}
In the component I added the field in rules:
<?php
namespace App\Http\Livewire;
use App\Models\Models\Platform;
use Livewire\Component;
class PlatformForm extends Component
{
public Platform $platform;
protected $listeners = ['recordToEdit' => 'editPlatform', 'newRecord' => 'createPlatform'];
protected $rules = [
'platform.id' => 'sometimes',
'platform.name' => 'sometimes',
'platform.created_at' => 'sometimes',
'platform.updated_at' => 'sometimes',
'platform.mydate_br' => 'sometimes',
];
public function mount() {
$this->platform = $this->makeBlankPlatform();
}
public function makeBlankPlatform()
{
return Platform::make();
}
public function editPlatform(Platform $platform)
{
$this->platform = $platform;
}
public function createPlatform()
{
$this->platform = new Platform();
$this->platform->created_at = now();
}
public function save()
{
$this->platform->id
? $this->platform->updated_at = now()
: $this->platform->updated_at = $this->platform->created_at;
$this->platform->save();
$this->emit('refresh');
}
public function render()
{
return view('livewire.platform-form');
}
}
And in the view I added the wire:model, like this:
<div>
<div class="form-group">
<label for="name">Name</label>
<input wire:model.defer="platform.name" type="text" class="form-control">
</div>
<div class="form-group">
<label for="mydate_br">My date</label>
<input id="mydate_br" wire:model.defer="platform.mydate_br" type="text" class="form-control">
</div>
<div class="form-group">
<label for="created_at">Created at</label>
<input id="created_at" wire:model="platform.created_at_br" type="text" class="form-control" readonly>
</div>
<div class="form-group">
<label for="updated_at">Updated at</label>
<input id="updated_at" wire:model="platform.updated_at_br" type="text" class="form-control" readonly>
</div>
<hr class="border">
<div class="text-right">
<button type="button" class="btn btn-secondary" data-dismiss="modal">
Cancelar
</button>
<button wire:click="save" type="button" class="btn btn-primary" data-dismiss="modal">
Gravar
</button>
</div>
</div>
The problem is that the date stored in the database is not displayed in the input text, however, if I do it in the standard blade way, {{ $platform->mydate_br }}, the value is displayed, but here I lose functionality of livewire binding.
Anyone have a tip to help me resolve this?
Related
In login form i used livewire and when i out focus of phone field my webpage its been white
please help me thanks <3
view code:
<form wire:submit.prevent="login">
<fieldset class="form-label-group form-group position-relative has-icon-left">
<input wire:model.debounce.500ms="phone" type="text" class="form-control" id="phone" placeholder="شماره تماس">
<div class="form-control-position">
<i class="feather icon-phone"></i>
</div>
<label for="phone">شماره تماس</label>
</fieldset>
#error('phone') <span class="text-danger">{{ $message }}</span> #enderror
<button type="submit" class="btn btn-primary float-left btn-inline" wire:click.prevent="login">ورود</button>
</form>
controller code:
class Login extends Component
{
public $phone;
protected $rules = [
'phone' => ['required', 'regex:/^09(1[0-9]|3[1-9]|2[1-9])-?[0-9]{3}-?[0-9]{4}$/', 'exists:users,phone']
];
public function updatedPhone($name)
{
$this->validate($name);
}
public function login(Request $request)
{
$validData = $this->validate();
$user = User::wherePhone($validData['phone'])->first();
dd($user);
$request->session()->flash('auth', [
'user_id' => $user->id,
'remember' => $request->has('remember'),
]);
$code = ActiveCode::generateCode($user);
$user->notify(new ActiveCodeNotification($code, $user->phone));
dd('done');
}
public function render()
{
return view('livewire.auth.login')
->layout('livewire.auth.layouts.layouts');
}
}
Your updatePhone method is supposed to receive $value from input binded with wire:model so you have to pass a key-value to validate method:
public function updatePhone($value)
{
$this->validate($this->rules); // protected prop with key-value rules defined
}
When I am editing my post then I am prompted with the following error message
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'content' => 'required',
'category_id' => 'required'
]);
$post = Post::find($id);
if($request->hasFile('featured'))
{
$featured = $request->featured;
$featured_new_name = time() . $featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$post->featured = 'uploads/posts/'.$featured_new_name;
}
$post->title = $request->title;
$post->content = $request->content;
$post->category_id = $request->category_id;
$post->save();
Session::flash('success', 'Post updated successfully.');
return redirect()->route('posts');
}
and blade code
<div class="form-group">
Select a Category
#foreach($categories as $category)
id}}"
#if($post->$category->id == $category->name)
selected
#endif
{{$category->name}}
#endforeach
List item
My Post method for post and category
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories'; // here set table's name
protected $primaryKey = 'id'; // here set table's primary Key field name
protected $fillable = ['id']; // here set all table's fields name
public function posts()
{
return $this->hasMany('App\Post');
}
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
public function category()
{
return $this->belongsTo('App/Category');
}
public function getFeaturedAttribute($featured)
{
return asset($featured);
}
use SoftDeletes;
protected $dates=['deleted_at'];
protected $fillable=['title','content','category_id','featured','slug'];
}
}
Edit.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header bg-info">
<div class="text-center">
<h4 class="m-b-0 text-white">
<div class="panel panel-default">
<div class="panel-heading">
Edit Post:{{$post->title}}
</div>
<div class="panel-body">
<form action="{{route('post.update', ['id'=>$post->id])}} " method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for ="title">Title</label>
<input type="text" name="title" class="form-control" value="{{$post->title}}">
</div>
<div class="form-group">
<label for ="featured">Featured image</label> <input type="file" name="featured" class="form-control">
</div>
<div class="form-group">
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for ="content">Content</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$post->content}}</textarea>
</div>
<div class="form-group">
<div class="text-center">
<button class="btn btn-success" type="submit"> Update Post</button>
</div>
</div>
</form>
</div>
</div>
</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Row -->
#stop
Controller...
public function store(Request $request)
{
$this->validate($request, [
'title' =>'required',
'featured'=>'required|mimes:jpeg,pdf,docx,png:5000',
'file'=>'required|mimes:jpeg,pdf,docx,png:5000',
'content'=>'required',
'category_id'=>'required',
]);
$featured= $request->featured;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$file=$request->file;
$file_name=time().$file->getClientOriginalName();
$file->move('uploads/posts', $file_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'featured'=>'uploads/posts/'. $featured_new_name,
'file'=>'uploads/posts'. $file_name,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
]);
Session::flash('success', 'New Blog has been Published on Website for Particular Menu');
return redirect()->back();
}
This the area in your blade where you are getting the issue:
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
Where are you fetching and providing $categories to this blade template? I mean the controller method which loads the edit blade?
Can you post that code as well?
And please update your question instead of posting answers.
I'm currently working with Laravel. I'm a novice and still trying to get used to the platform. I want to update my database based on form input but it's not working. I've tried updating models, views, and controllers and can't seem to get the database to update with input values.
My view:
<div class="form-group row">
<label class="col-xs-2 col-form-label">Expiration Date</label>
<div class="col-xs-10">
<input class="form-control" type="date" value="{{ $Document->expires_at }}" name="expires_at" placeholder="Expiration Date">
</div>
</div></form>
<embed src="{{ asset('storage/'.$Document->url) }}" width="100%" height="100%" />
<div class="row">
<div class="col-xs-6">
<form action="{{ route('admin.provider.document.update', [$Document->provider->id, $Document->id]) }}" method="POST">
{{ csrf_field() }}
{{ method_field('PUT') }}
<button class="btn btn-block btn-primary" type="submit">Approve</button>
</form>
</div></form>
My model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ProviderDocument extends Model
{
protected $table = 'provider_documents';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'provider_id',
'document_id',
'url',
'unique_id',
'status',
'expires_at',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
/**
* The services that belong to the user.
*/
public function provider()
{
return $this->belongsTo('App\Provider');
}
/**
* The services that belong to the user.
*/
public function document()
{
return $this->belongsTo('App\Document');
}
}
My controller:
public function update(Request $request, $provider, $id)
{
if(Setting::get('demo_mode', 0) == 1) {
return back()->with('flash_error', 'Disabled for demo purposes! Please contact us at info#appoets.com');
}
try {
$Document = ProviderDocument::where('provider_id', $provider)
->where('id', $id)
->firstOrFail();
$Document->update(['status' => 'ACTIVE']);
$Document->expires_at = $request['expires_at'];
$Document->save();
return redirect()->route('admin.provider.document.index', $provider)->with('flash_success', 'Provider document has been approved.');
}
catch (ModelNotFoundException $e) {
return redirect()->route('admin.provider.document.index', $provider)->with('flash_error', 'Provider not found!');
}
}
The database stays blank with no errors. If I manually put it in the database directly, then go to the form and update, it's deleted. Please help.
Thanks to the input of ##LimKeanPhang above, below is the end result. I didn't have to change the model or controller. Just the view. Worked like a charm.
<form class="form-horizontal" action="{{ route('admin.provider.document.update', [$Document->provider->id, $Document->id]) }}" method="POST">{{csrf_field()}}
<input type="hidden" name="_method" value="PATCH">
<div class="form-group row">
<label class="col-xs-2 col-form-label">Expiration Date</label>
<div class="col-xs-10">
<input class="form-control" type="date" value="{{ $Document->expires_at }}" name="expires_at" placeholder="Expiration Date">
</div>
</div>
<embed src="{{ asset('storage/'.$Document->url) }}" width="100%" height="100%" />
<div class="row">
<div class="col-xs-6">
<button class="btn btn-block btn-primary" type="submit">Approve</button>
</div>
</div>
</form>
Why don't you get the get the document by id only as follows ? Please try the following code. It should work.
The controller update function.
public function update(Request $request, $provider, $id)
{
if (Setting::get('demo_mode', 0) == 1) {
return back()->with('flash_error', 'Disabled for demo purposes! Please contact us at info#appoets.com');
}
try {
$Document = ProviderDocument::find($id);
$Document->status = 'ACTIVE';
$Document->expires_at = $request['expires_at'];
$Document->save();
return redirect()->route('admin.provider.document.index', $provider)->with('flash_success',
'Provider document has been approved.');
} catch (ModelNotFoundException $e) {
return redirect()->route('admin.provider.document.index', $provider)->with('flash_error',
'Provider not found!');
}
}
I want to submit some form information into my table, but this error is showing, if i do Route::resource('userinfo','infoController#index'); the error gone, but i can't insert data, what will be the solution.
My controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\infomodel;
class infoController extends Controller
{
public function index()
{
$alldata = infomodel::all();
return $alldata;
}
public function create()
{
return view('userinfo.create');
}
public function store(Request $request)
{
$input = $request->all();
infomodel:: create($input);
return redirect('infomodel');
}
}
My model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class infomodel extends Model
{
Protected $table = "info";
protected $fillable = ['name', 'email', 'age', 'hometown'];
}
My route web.php
<?php
Route::resource('userinfo','infoController');
Route::get('/solid', function () {
return view('solid.index');
});
This is view create.blade.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<title>Userinfo</title>
</head>
<body>
<div class="container" style="width:350px; margin:0 auto;
margin-top:25px;">
{!! Form::open(['route' => 'userinfo.store']) !!}
<div class="form-group">
<label for="name">Enter Your name</label>
<input type="text" class="form-control" name="name" placeholder="Enter name">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name= "email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="age">Age</label>
<input type="number" class="form-control" name="age" placeholder="Enter age">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Hometown</label>
<input type="text" class="form-control" name="hometown" placeholder="Enter hometown">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
{!! Form::close() !!}
</div>
</body>
</html>
The problem is in your store method
public function store(Request $request)
{
$input = $request->all();
infomodel:: create($input);
return redirect('infomodel');
}
You redirect user to non-existing route infomodel.
Try this
public function store(Request $request)
{
$input = $request->all();
infomodel:: create($input);
// You can try 'return back()' as well
return redirect()->route('userinfo.index');
}
I have item_color and item_size pivot tables, and would like to update my size and color fields using their field values, and an not exactly sure where to start. Here's what I have so far.
ItemSize.php
<?php
class ItemSize extends \Eloquent
{
protected $table = 'item_size';
protected $fillable = [];
public function item() {
return $this->belongsTo('Item');
}
}
ItemColor.php
<?php
class ItemColor extends \Eloquent
{
protected $table = 'item_color';
protected $fillable = [];
public function item() {
return $this->belongsTo('Item');
}
}
VendorController
public function postVendorUpdateItems ($id)
{
$input = Input::all();
$items = Item::find($id);
$validator = Validator::make($input,
[ 'item_name' => 'max:50',
'item_id' => 'max:50',
'normalprice' => 'numeric',
'karmaprice' => 'numeric',
'asin' => 'max:50',
]);
if($validator->passes())
{
$items->name = $input['item_name'];
$items->normalprice = $input['normalprice'];
$items->karmaprice = $input['karmaprice'];
$items->asin = $input['asin'];
$items->id = $input['item_id'];
$items->save();
return Redirect::route('account-vendor-index')
->with('global', 'You have updated your item.');
}
return Redirect::route('account-vendor-index')
->withErrors($validator)
->with('global', 'Your item could not be updated.');
}
View
<form class="form-horizontal" role="form" method="post" action="{{url('account/vendor/update/items')}}/{{$item->id}}">
<input type="hidden" id="brand_id" placeholder="brand_id" value="{{$brand->id}}" name="brand_id">
<input type="hidden" id="item_id" placeholder="item_id" value="{{$item->id}}" name="item_id">
<div class="form-group">
<label for="colors" class="col-xs-3 control-label">Colors</label>
<div class="col-xs-6">
<input type="text" class="form-control input-sm" id="colors" name="colors" placeholder="#foreach($item->colors as $color){{$color->color}}#endforeach" value="">
</div>
<button type="" class="btn btn-primary btn-sm">Add color</button>
<div class="clear"></div>
<div class="col-xs-offset-3 showColors">
#foreach($item->colors as $color)
{{$color->color}}
#endforeach
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Sizes</label>
<div class="col-xs-9">
<select id="selectSizes" multiple="multiple" class="form-control selectSizes" name="sizes">
<option value="XS (0-2)">XS (0-2)</option>
<option value="S (4-6)">S (4-6)</option>
<option value="M (8-10)">M (8-10)</option>
<option value="L (12-14)">L (12-14)</option>
<option value="XL (16-18)">XL (16-18)</option>
<option value="XXL (20-22)">XXL (20-22)</option>
</select>
</div>
</div>
<div class="form-group bot-0">
<div class="col-xs-offset-3 col-xs-9">
<button type="submit" class="btn btn-main btn-sm">Save changes</button>
</div>
</div>
</form>
item_size and item_color are not pivot tables. They are in fact a one to one relationship with your schema. If want you truly want are pivot tables, you need to define a color and a size table, then create a many-to-many relationship. See here: https://laravel.com/docs/master/eloquent-relationships
Then to update related models, you'll use the attach, sync, detach, etc. methods.
Also, what version of Laravel are you running? If you're running 5.1+ look into form request validation. See here: https://laravel.com/docs/master/validation#form-request-validation
That will remove all the validation logic from your controller.