AlyaKra
AlyaKra

Reputation: 566

Laravel : Update input with empty value

I have generated an API using Laravel.

In my controller I have the following function for the update :

public function update(Request $request, $id)
{
    $data = Link::find($id);
    $data->title = is_null($request->title) ? $data->title : $request->title;

    $data->save();    
}

What is basically does it that it verifies if the received input is null, it returns the default value, else it requests the new one.

The problem here is that when I update the input with an empty value such as 5 space characters, the input in the database doesn't receive the new value because it considers the space as null.

I have in mind maybe a solution like checking the number of characters in the received input. Like if the received string is less than 1 instead of is_null then return the default value . Is it right ?

Upvotes: 1

Views: 1135

Answers (1)

AlyaKra
AlyaKra

Reputation: 566

What I did is that I modified TrimStrings.php located in Middleware folder, and added the keys I wanted to exclude from that Middleware like the following :

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;

class TrimStrings extends Middleware
{
    /**
     * The names of the attributes that should not be trimmed.
     *
     * @var array
     */
    protected $except = [
        'password',
        'password_confirmation',
        'title',
        'description'
    ];
}

Like that those keys will not be using TrimStrings and therefore they can receive spaces as value.

Upvotes: 2

Related Questions