I'm new to laravel and i encountered an array to string conversion error while trying to send tags select form data to sync with my blogs table.
Below is blade snippet that retrieves tags from the database
<div class="form-group">
<label for="tag" class="control-label">Tags</label>
{!! Form::select('tag[]', $tags, old('tag'), ['class' => 'form-control select2', 'multiple' => 'multiple', 'id' => 'add-tag' ]) !!}
</div>
The BlogsController
$blog_data = request()->validate([
'tag.*' => 'required'
]);
blogs = Blog::create( $blog_data );
$blogs->tags()->sync((array)request()->input('tag'));
when i perform a dd on request()->tag
array:2 [▼
0 => "1"
1 => "2"
]
Just use like this
$blogs = Blog::create( $blog_data );
If insert then use like this
$blogs->tags()->attach($request->tag);
If update then use like this
$blogs->tags()->sync($request->tag);
Thank you, i was able to remove this line of code and it worked
tag.*' => 'required'
Related
I have a problem when import data xlsx using package fast excel.
I wanna input excel files include the Id from different model like following below
app/http/clustercontroller :
public function Import($id)
{
$model = Cluster::findOrFail($id);
return view('components.Admin.import', compact('model'));
}
public function StoreImport($id, Request $request)
{
//VALIDASI
$this->validate($request, [
'file' => 'required|mimes:xls,xlsx',
]);
if ($request->hasFile('file')) {
$file = $request->file('file'); //Get File
$collection = (new FastExcel)->import($file, function ($line) use ($id) {
return Soal::create([
'soal' => $line['Soal'],
'image' => $line['Image'],
'A' => $line['A'],
'B' => $line['B'],
'C' => $line['C'],
'D' => $line['D'],
'E' => $line['E'],
'kunci' => $line['Kunci'],
'cluster_id' => $id
]); //Import File
});
}
}
resource/admin/import.blade.php :
{!! Form::model($model, [
'route' => $model->exists ? ['cluster.soal.store', $model->id] : 'cluster.soal.create',
'method' => $model->exists ? 'POST' : 'POST',
'files' => true
]) !!}
<div class="form-group">
<label for="" class="control-label">Cluster</label>
{!! Form::text('cluster', null, ['class' => 'form-control', 'id' => 'cluster']) !!}
</div>
<div class="form-group">
<label for="" class="control-label">File .xlsx</label>
{!! Form::file('files') !!}
</div>
{!! Form::close() !!}
the code above displays the form, but when I click submit there is no response
You don't seem to return a response in your Controller method, so that's one reason I can think of. I assume your models are stored?
Things you could do to improve:
Return a view or, even better, redirection after finishing the import
Surround your code with try/catch blocks
Hello friends I need make a Textarea with Laravel Collective, regulary I use:
<textarea id="txt" name="txt" maxlength="1900" class="form-control" rows=1" onkeypress="return nameFunction(event);">My text</textarea>
How to create a textarea wiht Laravel Collective?
Try like this:
Form::textarea('My text', null, [
'class' => 'form-control',
'rows' => 1,
'name' => 'txt',
'id' => 'txt',
'onkeypress' => "return nameFunction(event);"
])
Here is an action:
public function postMessageAjax(Request $request)
{
$this->validate($request, [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
$message = new Message();
$message->username = $request->get('username');
$message->email = $request->get('email');
$message->homepage = $request->get('homepage');
$message->text = strip_tags($request->get('text'));
$message->ip = $request->ip();
$message->browser = get_browser($request->header('User-Agent'))->browser;
$message->save();
return view('Guestbook.postMessage');
}
And here is the view:
{!! BootForm::open(['id' => 'messageForm']) !!}
{!! BootForm::text('username') !!}
{!! BootForm::email('email') !!}
{!! BootForm::text('homepage') !!}
{!! BootForm::textarea('text') !!}
{!! captcha_img('flat') !!}
{!! BootForm::text('captcha') !!}
{!! BootForm::submit('Send') !!}
{!! BootForm::close() !!}
The problem is that Laravel somehow determines that that is an Ajax request and set an JSON of errors (if they're present) to Response instead of retrieving HTML code of form plus errors messages for each input individually. The question is: how do I force it to render the view with errors like if it weren't through Ajax?
UPDATE: this is what I want to get (the form itself and errors if they're present):
For #OuailB:
I've just noticed that when I do a normal POST request, it redirects me to the same page through a GET request so it seems like the error messages actually appear in the GET's body, not POST's so maybe there is no way. I'll think about it, thanks for your help!
You can create validator manually, and if it fails return what you want:
$validator = Validator::make($request->all(), [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput($request->all());
}
Try this code:
public function postMessageAjax(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
if ($validator->fails()) {
return view('Guestbook.postMessage')
->withErrors($validator);
}
// Store your message here
}
Edit :
For displaying the errors, you can add this code into your view :
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I want to show multiple selected values in laravel5.3 form
{!! Form::select('category[]', $categories['all_cat']['categories'], null,['multiple' => 'multiple'], ['class' => 'form-control', 'id' => 'category']) !!}
Try with this:
{!! Form::select('category[]', $categories['all_cat']['categories'], null, ['multiple' => true, 'class' => 'form-control', 'id' => 'category']) !!}
No matter which validation rule i brake as long as i have an array notation in input name like this
<div class="form-group">
{!! Form::label('titile', '* Eventname: ', ['class' => 'control-label']) !!}
{!! Form::text('title[]', null, ['class' => 'form-control', 'required']) !!}
</div>
i get this error:
I have tried to use simple plain html input like this
<input type="text" name="title[]" />
and even like this
{!! Form::text('title', null, ['name' => 'title[]','class' => 'form-control', 'required']) !!}
But nothing works.
Only if i make the input field without array notation [] the validation works properly...
my validation rule is this
$this->validate($request, [
'title' => 'required|min:2',
]);
I don't know what else to do, if anyone had similar problem please help.
UPDATE:
i have tried it like this now with only one form input:
<div class="form-group">
{!! Form::label('title', '* Eventname: ', ['class' => 'control-label']) !!}
{!! Form::text('title', null, ['name' => 'title[]','class' => 'form-control', 'required', 'placeholder' => 'z.B. Deutscher Filmpreis']) !!}
</div>
-
public function rules()
{
$rules = [
];
foreach($this->get('title') as $key => $val)
{
$rules['title.'.$key] = 'numeric';
}
return $rules;
}
Write your validation in individual request file. This ('title' => 'required|min:2') validation does not work for array input. Try this technique for dynamic field validation.
public function rules()
{
$rules = [
];
foreach($this->request->get('title') as $key => $val)
{
$rules['title.'.$key] = 'required|min:2';
}
return $rules;
}
Very Good example at laravel news site.
https://laravel-news.com/2015/11/laravel-5-2-a-look-at-whats-coming/
OK i finally solved this. In Laravel 5.3 something is changed and you can't put empty array brackets for field name.
You must declare indices inside...for example:
this doesn't work
{!! Form::text('title[]', null, ['class' => 'form-control', 'required']) !!}
but this works
{!! Form::text('title[0]', null, ['class' => 'form-control', 'required']) !!}
UPDATE
So after solving this now i know that if you put empty [ ] brackets this will work if you have multiple input fields with same name...but if you put empty brackets and you have an option to add new fields dynamically like i did...then that single field with empty array brackets will fail because you actually don't have an array...and you must put [0] some indices inside...
and then it works