Pass empty fields on the update method using Laravel Request
I'm getting data through a classic submitted form but for some reason I don't get all the input's data in request and it only updates the received ones.
Model::find($id)->update($request->all());
This is a bit problematic because I have multiple nullable fields in my database and sometimes I want to pass empty fields (i.e when a user clear an input then submit the form)
Do you know a way to pass empty fields to the Request as well?
3 answers
-
answered 2018-07-12 06:19
HCK
The thing is, Laravel transforms the
''
values tonull
by default through the ConvertEmptyStringsToNull middleware. Check your Kernel:app/Http/Kernel.php
protected $middleware = [ // some middlewares.. \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, // some more middlewares.. ];
This middleware do the following:
protected function transform($key, $value) { return is_string($value) && $value === '' ? null : $value; }
As you can see, if the given attribute has a value
''
it will be transformed tonull
.So, to avoid this you could just comment that middleware in the Kernel file. But be aware of this, because this will be applied to your entire application.
-
answered 2018-07-12 07:11
DolDurma
You can use php
array_merge()
like with this code as i use that$contentCategory->update(array_merge($request->all(), ["FIELD1" => '',"FIELD2" => '']));
or test this code:
$request->request->add(['FIELD1' => '','FIELD2' => '']);
-
answered 2018-07-12 15:17
Talha Siddiqi
Input Trimming & Normalization
Laravel version > 5.4 already has these features included:
For versions < 5.4: make a new middleware with following code:
public function handle($request, Closure $next) { foreach ($request->input() as $key => $value) { if (! $value) { $request->request->set($key, NULL); } } return $next($request); }
and assign it to the routes or controller's methods you want it to take place:
Route::post('/route/{id}', [ 'middleware' => NewMiddleware::class, ], function (Request $request, $id) { Model::find($id)->update($request->all()); });
REMEMBER:
create()
,update()
, etc. methods work on fields in$fillable
array in your model. If your field is not in the$fillable
array in "Model" class, theupdate()
method will not work for that field!!!
See also questions close to this topic
-
Laravel FFMpeg encoding failed
I'm using Laravel FFMpeg to encode videos and create thumbnails, but none of them are working. Whenever I try to create a thumbnail or encode a video I get following error:
ffmpeg failed to execute command '/usr/local/bin/ffmpeg' '-y' '-i' '/home/diego/dynamic4/bg/storage/app/public/activity/4942/cLCbKyLiGqbOb0M5JDtvNXUdzSxFGj9ts6sDZb4D.mp4' '-threads' '12' '-vcodec' 'libx264' '-acodec' 'libfaac' '-b:v' '1000k' '-refs' '6' '-coder' '1' '-sc_threshold' '40' '-flags' '+loop' '-me_range' '16' '-subq' '7' '-i_qfactor' '0.71' '-qcomp' '0.6' '-qdiff' '4' '-trellis' '1' '-b:a' '128k' '-pass' '1' '-passlogfile' '/tmp/ffmpeg-passes5c6378517cace4u1cg/pass-5c6378517cb33' '/home/diego/dynamic4/bg/storage/app/public/1234.mp4'
If I check that error on console I get this:
ffmpeg failed to execute command '/usr/local/bin/ffmpeg' '-y' '-i' '/home/diego/dynamic4/bg/storage/app/public/activity/4942/cLCbKyLiGqbOb0M5JDtvNXUdzSxFGj9ts6sDZb4D.mp4' '-threads' '12' '-vcodec' 'libx264' '-acodec' 'libfaac' '-b:v' '1000k' '-refs' '6' '-coder' '1' '-sc_threshold' '40' '-flags' '+loop' '-me_range' '16' '-subq' '7' '-i_qfactor' '0.71' '-qcomp' '0.6' '-qdiff' '4' '-trellis' '1' '-b:a' '128k' '-pass' '1' '-passlogfile' '/tmp/ffmpeg-passes5c6377a214b41rk6ao/pass-5c6377a214b7b' '/tmp/laravel-ffmpegObuaI1.mp4' ffmpeg version 4.1-1~18.04.york1 Copyright (c) 2000-2018 the FFmpeg developers built with gcc 7 (Ubuntu 7.3.0-27ubuntu1~18.04) configuration: --prefix=/usr --extra-version='1~18.04.york1' --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --arch=amd64 --enable-gpl --disable-stripping --enable-avresample --disable-filter=resample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librsvg --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-nonfree --enable-libfdk-aac --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared libavutil 56. 22.100 / 56. 22.100 libavcodec 58. 35.100 / 58. 35.100 libavformat 58. 20.100 / 58. 20.100 libavdevice 58. 5.100 / 58. 5.100 libavfilter 7. 40.101 / 7. 40.101 libavresample 4. 0. 0 / 4. 0. 0 libswscale 5. 3.100 / 5. 3.100 libswresample 3. 3.100 / 3. 3.100 libpostproc 55. 3.100 / 55. 3.100 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/home/diego/dynamic4/bg/storage/app/public/activity/4942/cLCbKyLiGqbOb0M5JDtvNXUdzSxFGj9ts6sDZb4D.mp4': Metadata: major_brand : mp42 minor_version : 1 compatible_brands: mp41mp42isom creation_time : 2018-10-22T15:38:46.000000Z Duration: 00:00:58.36, start: 0.000000, bitrate: 1400 kb/s Stream #0:0(und): Video: h264 (Baseline) (avc1 / 0x31637661), yuv420p(tv, bt709), 848x480, 1334 kb/s, 30.01 fps, 30 tbr, 600 tbn, 1200 tbc (default) Metadata: creation_time : 2018-10-22T15:38:46.000000Z handler_name : Core Media Video Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 62 kb/s (default) Metadata: creation_time : 2018-10-22T15:38:46.000000Z handler_name : Core Media Audio [NULL @ 0x55fecc7a0280] Unable to find a suitable output format for 'failed' failed: Invalid argument
I have checked permissions and everything looks ok. I have also checked the video I'm trying to encode exists. It does, and apparently it get properly loaded. It seems to fail when trying to save encoded file. I spent one day doing research, I tried with different audio & video encoding, different routes and filesystems, but I couldn't make it work. I have also tried to check that passlogfile (
/tmp/ffmpeg-passes5c6377a214b41rk6ao/pass-5c6377a214b7b
) but as it gets stored under/tmp
I can't gain access to it.Any help much appreciated, thanks!
-
Laravel: Jobs failed - SQLSTATE[42S02]: Base table or view not found
I'm developing a Multi Tenant with Laravel v5.7 and I'm successful in sending queue emails, since my models have the property 'connection' defined.
But when trying to send, for example, an email using the Jobs class, the same fails and informs that the table of model does not exist.
From what error recorded in the table 'failed_jobs', even with the property 'connection' defined, it appears that the Job nevertheless tries to connect to the main database and not to the specified database of the property.
Is there any way to specify in Job which database to use, since the same is informed in the model?
database.php
'connections' => [ 'others' => ['...'] 'TENANT001' => [ 'driver' => 'mysql', 'database' => env('TENANT001_DATABASE', ''), 'host' => env('TENANT001_HOSTNAME', ''), 'port' => env('DB_PORT', '3306'), 'username' => env('TENANT001_USERNAME', 'forge'), 'password' => env('TENANT001_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ],
],
Sample Model
class Template extends Model { /** * The database name used by the model. * * @var string */ protected $connection = 'TENANT001'; }
failed_jobs
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'main_database.templates' doesn't exist in /www/samba/laravel.local/vendor/laravel/framework/src/Illuminate/Database/Connection.php:326
-
404 no errors displaying in laravel, how can I debug this/fix this update route?
I have created a has many relationships with a task model (many tasks to 1 project model) and set up a button to say if a task has been completed or not (1 or 0).
When I click the button to update the database with (as shown in the view) I receive this 404 instead (See pic) instead of the usual error screen which laravel usually throws out, checked the logs no errors there either.
I have attached the code and the network error that comes with the 404 but I don't really know what I am looking for in there if someone can point me in the right direction with 404 error or if there is a mistake in the code below, I would be most grateful!
view
<form method="POST" action="/tasks/{{ $task->id }}"> @method('PATCH') @csrf <label for="completed"> <input type="checkbox" name="completed" onChange="this.form.submit()"> {{ $task->description }} </label> </form>
Controller
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Task; class ProjectTasksController extends Controller { public function update() { dd('foo'); } }
Route
Route::patch('/tasks/{$task}', 'ProjectTasksController@update');
Migration
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTasksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tasks', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('project_id'); $table->string('description'); $table->boolean('completed')->default(false); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tasks'); } }
Model
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Task extends Model { protected $fillable = [ 'project_id', 'description', 'completed' ]; public function project() { return $this->belongsTo(Project::class); } }
-
adding elements to certain indexes in an array based on user input from a form (HTML/Javascript)
So I have an array with 23 indexes. I have 23 forms for user input as well. each form should add to certain index in the array after user enters an input. I try get the input with
onekeyup
function. For example the first form should only add values to the first index in the array and so on. What's the best way to do it?This is my array and function(which doesn't work):
Var dps=[] function a(){ dps = document.getElementById().value; }
These are my inputs:
<input type="number" class="form-control" id="skill1" onkeyup="a()"> <input type="number" class="form-control" id="skill2" onkeyup="a()"> <input type="number" class="form-control" id="skill3" onkeyup="a()"> . . . <input type="number" class="form-control" id="skill23" onkeyup="a()">
-
How to make an upload form which requires rights
So I have a Php function in a form for file upload and I want to force people, that want to upload files, to log in. So if someone clicks on upload, an like in-window-pop-up comes up and he is forced to log himself in, or the upload will be canceled.
How do I do that?
index.html
<!DOCTYPE HTML> <html> <head> <title> File-Upload </title> <link style="text/css" rel="stylesheet" href="design.css"/> </head> <body> <div class="form"> <form action="upload.php" method="post" enctype="multipart/form-data"> <input class="select" type="file" name="datei"><br> <input class="upload" type="submit" value="Hochladen"> </form> </div> </body> </html>
upload.php
<?php $upload_folder = 'uploads/'; $filename = pathinfo($_FILES['datei']['name'], PATHINFO_FILENAME); $extension = strtolower(pathinfo($_FILES['datei']['name'], PATHINFO_EXTENSION)); $allowed_extensions = array('png', 'jpg', 'jpeg', 'gif', 'zip', 'rar', 'txt'); if(!in_array($extension, $allowed_extensions)) { die("Ungültige Dateiendung. Nur png, jpg, jpeg, gif, zip, rar und txt-Dateien sind erlaubt"); } $max_size = 1000*1024; //500 KB if($_FILES['datei']['size'] > $max_size) { die("Bitte keine Dateien größer 1000kb hochladen"); } $new_path = $upload_folder.$filename.'.'.$extension; if(file_exists($new_path)) { $id = 1; do { $new_path = $upload_folder.$filename.'_'.$id.'.'.$extension; $id++; } while(file_exists($new_path)); } move_uploaded_file($_FILES['datei']['tmp_name'], $new_path); echo 'Bild erfolgreich hochgeladen: <a href="'.$new_path.'">'.$new_path.'</a>'; ?>
I'm sorry for the German, but I think you can imagine what that would be in English.
-
PHP email form almost works
I'm using an HTML5/CSS template with a built in contact form. My contact.php file is in place and the form is working as expected except for the most important part. The email is not being sent. I might be missing a necessary line or two. Here's the form and php code, with the recipient address "name@domain.com", but no mail ever reaches the inbox. The php version is 7.2 on a greengeeks host.
<?php $field_name = $_POST['InputName']; $field_email = $_POST['InputEmail']; $field_message = $_POST['InputMessage']; $mail_to = 'name@domain.com'; $subject = 'Message from a site visitor '.$field_name; $body_message = 'From: '.$field_name."\n"; $body_message .= 'E-mail: '.$field_email."\n"; $body_message .= 'Message: '.$field_message; $headers = 'From: '.$field_email."\r\n"; $headers .= 'Reply-To: '.$field_email."\r\n"; $mail_status = mail($mail_to, $subject, $body_message, $headers); if ($mail_status) { ?> <script language="javascript" type="text/javascript"> alert('Thank you for the message. We will contact you shortly.'); window.location = 'index.html'; </script> <?php } else { ?> <script language="javascript" type="text/javascript"> alert('Message failed. Please, send an email to webmaster@domain.com'); window.location = 'index.html'; </script> <?php } ?>
-
STL Unordered_map not holding key/value pair after assignment
I am trying to write an Input Manager class in C++ which simply stores the current state of different keys as either pressed or not. The method
PressKey
is called whenever GLFW registers a key_callback event.Private member variable:
std::unordered_map<unsigned int, bool> m_keyMap;
I have defined 2 methods of relevance:
void InputManager::PressKey(unsigned int keyID) { m_keyMap[keyID] = true; } bool InputManager::IsKeyPressed(unsigned int keyID) { auto it = m_keyMap.find(keyID); if (it != m_keyMap.end()) { // Found the key return it->second; } else { // Didn't find the key return false; } }
Basically after some testing I found that
m_keyMap.find(keyID)
always returns the end list iterator.Testing the value of
m_keyMap[keyID]
immediately inside the PressKey method shows that the value is true when the key is pressed but doesn't work inside the IsKeyPressed method.There are no other methods which modify the state of
m_keyMap
. -
Check if user selected all in shiny pickerInput menu
I have a shiny application with several pickerInput menus. They amount of choices change in each menu based on the selections of other menus so I can't ever hard code anything (ex: menu A will have 4 total selections possible).
I am trying to determine how to check if the user selected all of the possible values in a menu (pickerInput has a built in Select All button).
An example of how my pickerInput menus are structured:
choices <- c("apple", "pear", "orange") pickerInput(inputId = "A", label = "Menu A:", choices = c(sort(na.omit(choices))), options = list(`actions-box` = T, `none-selected-text` = "Please make a selection."), multiple = T)
In the above code example there are (hard coded) 3 choices, however, in my real app this may vary. In this example, to find out if all choices were selected, I could simply check if 3 selections were stored in
input$A
.I am looking to generalize this, I checked the documentation and am not finding any built-in way of checking if a user selected all of the choices in a
pickerInput
menu. So I am looking for an alternative way of checking this. -
how to copy dynamically (synchronously) text typed in an input field to a text svg in javascript or jquery?
I want to do the same thing as the following example but replace the second input with id bar by the svg text tag with id bar.
$(function(){ var $foo = $('#foo'); var $bar = $('#bar'); function onChange() { $bar.val($foo.val()); }; $('#foo') .change(onChange) .keyup(onChange); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <input id="foo" /> <input id="bar" />
-
Fetch Request Body from org.springframework.web.reactive.function.BodyInserter
I have the below code where I am able to log the headers and URL. But the body() method is returning an object of type BodyInserter. In the debug mode(STS), we can see the request body object. Is there any way to log the request?
[private ExchangeFilterFunction logRequest() { return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> { loggingService.info(clientRequest.url()); loggingService.info(clientRequest.headers()); BodyInserter<?, ? super ClientHttpRequest> bodyInserters= clientRequest.body(); return Mono.just(clientRequest); }); }
-
Conditional routing in Symfony 4
Using the documentation left by the fabulous people of Symfony I'd like to match a route when a specific query string is being passed. I've debugged it to death but it seems like it isn't meant to work this way, although I cannot interpret but that it should work from the docs.
Simply put, I'd like to match a route with conditions via PHP Annotations. This, of course, requires me to enable annotations and the Expression Language component. All perfectly working, but when I use the
query
portion of the request object in EL(Expression Language) it doens't work.The HttpFoundation Request object is as follows. It clearly states the "query" as a property, thus having
query.has('key')
andquery.get('key') == 'value'
. It has bothcontext.
andrequest.
in this language, though query is empty. When I edit the cache, the line clearly hasqueryParams: "v=test"
. The following should work without any problems, but to no avail./** @Route("/test", name="testcondition", condition="request.query.has('v') and request.query.get('v') == 'test'")
No cigar. Remove the condition part and it works just fine. Leave the
.has
check and it stops working, because it's empty.What am I doing wrong? I'm completely up to date.
symfony/routing v4.2.3 Symfony Routing Component symfony/http-foundation v4.2.3 Symfony HttpFoundation Component symfony/http-kernel v4.2.3 Symfony HttpKernel Component symfony/expression-language v4.2.3 Symfony ExpressionLanguage Component sensio/framework-extra-bundle v5.2.4 This bundle provides a way to configure your controllers with annotations Symfony Version 4.2.3 End of maintenance 07/2019 End of life 01/2020
-
how to calculate resume and pause data amount in progress bar
How can I calculate received data after I pause and resume a function.
I'm working on file download, including download pause and resume.
It pauses ok, but when I resume it, it doesn't go to 100%. it stops before 100%
function download_file(event, filename) { req2 = request({ method: 'GET', uri: fileURL }); var out = fs.createWriteStream(finalPath); req2.pipe(out); req2.on('response', function(data) { total_bytes = parseInt(data.headers['content-length']); progressBar.max = total_bytes; total_size = total_bytes; }); req2.on('data', function(chunk) { received_bytes += chunk.length; console.log(received_bytes); progressBar.value = received_bytes; display.innerText = Math.round((progressBar.value / progressBar.max) * 1000) / 10 + '%' } }); }; function pause22() { console.log('pause function called'); req2.pause(); } function resume22() { console.log('RESUME function called'); progressBar.max=progressBar.max-progressBar.value; console.log(progressBar.max); console.log(progressBar.value); progressBar.value = received_bytes; received_bytes= progressBar.value; req2.resume(); }
-
How i will send notification to seller in mobile app when customer submit the order for their product
I need Rest API in php for notification in mobile app. When customer submit their order through app then the seller will get notified in their app that this user placed a order for your product.
How the notification will work and what is the process to make the rest api in php for this process.
-
Store field value in Wordpress session with ajax submit on change field
I am having this form:
<form method="get"> <input type="text" id="datepicker" placeholder="Choose a date" name="wapbk_hidden_date" value=""> </form>
What I want to achieve is when changing this form field, so change input#datepicker it needs to ajax pass the value into the WordPress session so on any page after doing this the value can be loaded and echo while being in the same session with:
$wapbk_hidden_date = $_GET['wapbk_hidden_date'];
Can someone help me?
-
Octave: problem with curl -coursera machine learning submission
I have been getting a submission error as follows while trying to send an assignment :
curl -sS -k -X POST -d @- https://www -origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1"' Function: submitWithConfiguration>getResponse FileName: F:\project\machine-learning\machine-learning-ex6\ex6\lib\submitWithConfiguration.m LineNumber: 137 Please correct your code and resubmit. And line 137 is as follows : function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -sS -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -sS -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method %LINE137 [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end
I have been stuck submitting the assignment. I have tried some alternatives like
--silent
tag and-sS
tag (as can be seen in the if statement inside sprintf) but of no use.Is there any workaround to get past this problem?