1

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 ?

7
  • 1
    'it considers the space as null'. That is not true, Laravel has a ConvertEmptyStringsToNull middleware which removes the spaces. Commented May 10, 2021 at 11:31
  • @Daan I see. So how can receive spaces in this case. Commented May 10, 2021 at 11:33
  • You disable the middleware. Commented May 10, 2021 at 11:33
  • @Daan Only in that controller? What if I need it somewhere else? Commented May 10, 2021 at 11:34
  • The middleware has an except property, you can define which routes you want to have excluded. Commented May 10, 2021 at 11:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.