Laravel Must be string when saving - laravel

I have a mounted variable and an error occurs when i'm about to save the variable.
public $code;
public function mount()
{
$this->code = substr(str_shuffle(str_repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 5)), 0, 3).Carbon::now()->format('md').rand(100, 999);
}
protected function rules(): array
{
return [
'applicant.code' => [
'string',
'required',
],
];
}
blade
<div class="form-group {{ $errors->has('applicant.code') ? 'invalid' : '' }}">
<label class="form-label" for="code" hidden>{{ trans('cruds.applicant.fields.code') }}</label>
<input class="form-control" type="text" name="code" id="code" value="{{ $code }}" disabled hidden>
<div class="validation-message">
{{ $errors->first('applicant.code') }}
</div>
<div class="help-block">
{{ trans('cruds.applicant.fields.code_helper') }}
</div>
</div>
<div class="form-group">
<button class="btn btn-indigo mr-2" type="submit">
{{ trans('global.submit') }}
</button>
<a href="{{ route('admin.applicants.index') }}" class="btn btn-secondary">
{{ trans('global.cancel') }}
</a>
</div>
The code must be a string.
I can't seem to figure out this error. Can anyone help?

<input class="form-control" type="text" name="code" id="code" value="{{ $code }}" disabled hidden>
Your input code is disabled

function mount() {
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$date = date("md");
$numbers = rand(100, 999);
$randomString = substr(str_shuffle(str_repeat($characters, 5)), 0, 3). $date . $numbers;
return $randomString;
}
echo mount();

Your rule defines applicant.code, therefore the validation is expecting a variable named applicant with a key named code:
public array $applicant = [
'code' => null,
];
public function mount()
{
$this->applicant['code'] = ''; // Implement your code
}
Also, you have an input showing the code in your blade view. Is this meant to be editable? If so, you should be using wire:name instead of name (See docs).
However, since you have it disabled, I don't assume you want to allow the user to edit it, so why have it validated in the first place?

Related

laravel livewire Save file using file name

I'm trying to save uploaded pdf files but the pdf file name changes on the storage link. is there any way to retain the original file name when saving?
public $code, $pdfs;
public function mount(Applicant $applicant)
{
$this->code = substr(str_shuffle(str_repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 5)), 0, 3).Carbon::createFromFormat('Y-m-d H:i:s', now())->format('md').rand(100, 999);
}
public function submit(Request $request)
{
$this->validate([
'pdfs.*' => 'mimes:pdf',
]);
$filenames = collect($this->tests)->map->store($this->code.'/', 'public');
return redirect()->route('careers.vacant');
}
here's my blade
<form wire:submit.prevent="submit" class="pt-3" enctype="multipart/form-data">
<div class="form-group">
<label class="form-label required" for="code" >Application {{ trans('fields.code') }}</label>
<input class="form-control" type="text" name="code" id="code" wire:model.defer="code" >
<div class="validation-message">
{{ $errors->first('code') }}
</div>
<div class="help-block">
{{ trans('fields.code_helper') }}
</div>
</div>
<input type="file" name="pdf" id="pdf" wire:model="pdfs" multiple >
<div wire:loading wire:target="pdfs">Uploading...</div>
#error('pdfs.*') <span class="error">{{ $message }}</span> #enderror
<div class="form-group">
<button class="mr-2 btn btn-indigo" type="submit">
{{ trans('global.submit') }}
</button>
<a href="{{ route('admin.applicants.index') }}" class="btn btn-secondary">
{{ trans('global.cancel') }}
</a>
</div>
</form>
I need to save the pdfs like this:
$filenames = collect($this->tests)->map->store($this->code.'/'.pdfFileName, 'public');
EDIT:
foreach ($this->tests as $file) {
$name = $file->getClientOriginalName();
$file->store('moca/'.$this->code.'/'.$name, 'public');
}
I tried this code but in the path $name becomes a folder instead of becoming the name of the file
You can try this:
$request->file('pdf')->getClientOriginalName() will return the original name of file

Edit two unique value with laravel

I have a problem with my Laravel 5.8 project. I want to edit one of two field that both have unique value.
Blade:
#extends('layouts.master')
#section('content')
<h1>CHANGE SURGICAL DIVISION</h1>
<a href="/surgical-div">
<button type="button" class="btn btn-primary btn-sm">BACK</button><br>
</a>
#if (session('mess'))
<div class="alert alert-success">
{{ session('mess')}}
</div>
#endif
<form method="POST" action="/surgical-div/{{ $surgicaldivs->id_surgical_div }}">
#method('patch')
#csrf
<div class="form-group">
<label for="name_surgical_div">Surgical Division Name: </label>
<input type="text" value="{{ $surgicaldivs->name_surgical_div }}"
class="form-control #error('name_surgical_div') is-invalid #enderror" id="name_surgical_div" name="name_surgical_div"
placeholder="Insert The Surgical Division">
#error('name_surgical_div')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="form-group">
<label for="initial_surgical_div">Surgical Division Initial : </label>
<input type="text" value="{{ $surgicaldivs->initial_surgical_div }}"
class="form-control #error('initial_surgical_div') is-invalid #enderror" id="initial_surgical_div" name="initial_surgical_div"
placeholder="Insert Surgical Division Initial">
#error('initial_surgical_div')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<button type="submit" class="btn btn-success btn-sm">Save</button>
</form>
#endsection
Controller:
public function edit($id)
{
$surgicaldivs = SurgicalDiv::withTrashed()->find($id);
return view('pages.surgical_div.surgical_div_edit', compact('surgicaldivs'));
}
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class SurgicalDiv extends Model
{
//Table Name
protected $table = 'surgical_div';
// Primary Key
protected $primaryKey = 'id_surgical_div';
//Soft Deletes
use SoftDeletes;
//Fillable Field
protected $fillable = ['name_surgical_div', 'initial_surgical_div'];
}
This is the update in the controller that i've tried :
public function update(Request $request, SurgicalDiv $SurgicalDiv)
{
$request->validate([
'name_surgical_div' => 'required|unique:surgical_div,name_surgical_div',
'initial_surgical_div' => 'required|unique:surgical_div,initial_surgical_div'
]);
SurgicalDiv::withTrashed()->where('id_surgical_div',$id)
->update([
'name_surgical_div' => $request->name_surgical_div,
'initial_surgical_div' => $request->initial_surgical_div
]);
return redirect('/surgical-div/'.$id.'/edit')->with('mess',' Surgical Division Change Success !');
}
I don't know what to put on the update function in the controller. I want to update one or even both of the field from my blade.
Try this
public function update(Request $request, SurgicalDiv $SurgicalDiv)
{
$request->validate([
'name_surgical_div' => 'required|unique:surgical_div,name_surgical_div,'.$id,
'initial_surgical_div' => 'required|unique:surgical_div,initial_surgical_div,'.$id
]);
SurgicalDiv::withTrashed()->where('id_surgical_div',$id)
->update([
'name_surgical_div' => $request->name_surgical_div,
'initial_surgical_div' => $request->initial_surgical_div
]);
return redirect('/surgical-div/'.$id.'/edit')->with('mess',' Surgical Division Change Success !');
}
This will check the table for same entries except the row with the $id. This way you can check if there are any other rows with same values in the two columns.

I got this error "Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type

When i try to insert data into my table this error occurs
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in C:\xampp\htdocs\Portal\vendor\laravel\framew...
view
<form method="post" action="{{ route('notice.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="Select Group to Post Notice">Select Group to Post Notice </label>
<select class="bg-white text-danger form-control " name='GroupID[]' multiple>
#foreach ($users as $user)
<option value="{{ $user->GroupID }}">{{ $user->GroupID }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="Enter Notice">Enter Notice</label>
<input class="bg-white text-danger p-2 form-control form-control-sm" type="text" name="Notice" placeholder="Enter Notice">
</div>
<input class="btn btn-danger btn-lg px-5" type="submit" name="submit">
</form>
controller
public function store(Request $request)
{
$member = $request->input('GroupID');
foreach($member as $value) {
$storeInfo = new notice();
$storeInfo->GroupID = $request->input('GroupID');
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('/notice');
}
I would imagine the reason you're getting this error is because of:
$storeInfo->GroupID = $request->input('GroupID');
$request->input('GroupID') will return an array (name='GroupID[]') and not an individual id.
Since you're already looping through the group ids you can instead use the value for the GroupId:
public function store(Request $request)
{
foreach ($request->input('GroupID') as $groupId) {
$storeInfo = new notice();
$storeInfo->GroupID = $groupId; //<--here
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('notice');
}
try changing controller logic
public function store(Request $request)
{
//
$member=$request->input('GroupID');
foreach($member as $value){
$storeInfo = new notice();
$storeInfo->GroupID = $value;
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('/notice');
}

Laravel - How to handle errors on PUT form?

I am working with laravel 5.2 and want to validate some data in an edit form. I goal should be to display the errors and keep the wrong data in the input fields.
My issue is that the input is validated by ContentRequest and the FormRequest returns
$this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
which is fine so far. Next step the edit action in the controller is called and all parameters are overwritten.
What I have currently done:
ContentController:
public function edit($id)
{
$content = Content::find($id);
return view('contents.edit', ['content' => $content]);
}
public function update(ContentRequest $request, $id)
{
$content = Content::find($id);
foreach (array_keys(array_except($this->fields, ['content'])) as $field) {
$content->$field = $request->get($field);
}
$content->save();
return redirect(URL::route('manage.contents.edit', array('content' => $content->id)))
->withSuccess("Changes saved.");
}
ContentRequest:
class ContentRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required|min:3'
];
}
}
How can I fix this? The form looks like this:
<form action="{!! URL::route('manage.contents.update', array('content' => $content->slug)) !!}"
id="site-form" class="form-horizontal" method="POST">
{!! method_field('PUT') !!}
{!! csrf_field() !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="title" placeholder="Title"
value="{{ $content->title }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
</form>
Try something like the following:
<input
type="text"
class="form-control"
name="title"
id="title"
placeholder="Title"
value="{{ old('title', $content->title) }}" />
Note the value attribute. Also check the documentation and find Retrieving Old Data.

Laravel 4 - Update many to many

I am currently trying to amend an update page which features a many to many relationship. It updates to my database perfectly, however all I'm trying to achieve now is to actually show the already selected items in my multiple select list in my view.
It currently just shows the entire list of oilgas jobs, just not the currently selected ones which should come from the query in some way.
So, it currently looks like this:
I need it to look like this, if Instrument Technician was previously chosen.
The associated files are as follows:
MODELS
OilGasJob.php
<?php
class OilGasJob extends \Eloquent {
protected $table = 'oilgasjobs';
public function industryjobs()
{
return $this->belongsToMany('IndustryJob');
}
}
IndustryJob.php
<?php
class IndustryJob extends \Eloquent {
protected $table = 'industryjobs';
public function oilgasjobs()
{
return $this->belongsToMany('OilGasJob');
}
}
CONTROLLER (CREATE PAGE AND STORE)
public function edit($id)
{
$industryjob = IndustryJob::find($id);
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This division job is not valid');
}
View::share('page_title', 'Edit Division Job');
return View::make('admin/industry-jobs/edit')->with('industryjob',$industryjob);
}
public function update($id)
{
$rules = array(
'job_title' => 'Required|Min:3|Max:80'
);
$validation = Validator::make(Input::all(), $rules);
If ($validation->fails())
{
return Redirect::back()->withErrors($validation);
} else {
$industryjob = IndustryJob::find($id);
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This divison job is not valid');
}
View::share('page_title', 'Edit Division Job');
$industryjob->job_title = Input::get('job_title');
$industryjob->slug = Str::slug(Input::get('job_title'));
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
$industryjob->save();
$industryjob->oilgasjobs()->sync(Input::get('oilgasjobs'));
return Redirect::to('/admin/industry-jobs')->with('message', 'Division Job updated successfully');
}
}
VIEW
{{ Form::open(array('url' => URL::to('admin/industry-jobs/edit/'.$industryjob->id), 'class'=>'form-horizontal', 'method' => 'POST')) }}
<div class="form-group">
<label class="col-md-2 control-label" for="industry_name">Job Title (*)</label>
<div class="col-md-10">
<input class="form-control" type="text" name="job_title" id="job_title" value="{{ $industryjob->job_title }}" />
</div>
</div>
<!-- Industry Type -->
<div class="form-group">
<label class="col-md-2 control-label" for="body">Related Jobs in Oil & Gas</label>
<div class="col-md-10">
<select name="oilgasjobs[]" id="oilgasjobs[]" size="6" class="form-control" multiple>
#foreach(OilGasJob::orderBy('job_title', 'ASC')->get() as $oilgasjob)
<option value="{{ $oilgasjob->id }}" >{{ $oilgasjob->job_title }}</option>
#endforeach
</select>
</div>
</div>
<!-- ./ Industry Type -->
<!-- Form Actions -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-success">Update Job</button>
</div>
</div>
<!-- ./ form actions -->
{{ Form::close() }}
In edit method add this code:
// ...
$linkedOilgasjob = DB::table('oilgasjob_industryjob')->lists('oilgasjob_id');
return View::make('admin/industry-jobs/edit'
,compact('industryjob')
,compact('linkedOilgasjob'));
Then in your view
<option value="{{ $oilgasjob->id }}" {{ in_array($oilgasjob->id,linkedOilgasjob) ? "selected='selected'" : "" }} >
{{ $oilgasjob->job_title }}
</option>
CONTROLLER
public function edit($id)
{
$data['industryjob'] = IndustryJob::find($id);
$data['oilgasjobs'] = DB::table('industry_job_oil_gas_job')->where('industry_job_id','=',$id)->lists('oil_gas_job_id');
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This division job is not valid');
}
View::share('page_title', 'Edit Division Job');
return View::make('admin/industry-jobs/edit', $data);
}
VIEW
<select name="oilgasjobs[]" id="oilgasjobs[]" size="6" class="form-control" multiple>
#foreach(OilGasJob::orderBy('job_title', 'ASC')->get() as $oilgasjob)
<?php
$selected = "";
if(in_array($oilgasjob->id, $oilgasjobs))
$selected = "selected";
?>
<option value="{{ $oilgasjob->id }}" <?php echo $selected; ?>>{{ $oilgasjob->job_title }}</option>
#endforeach
</select>

Resources