'What causes the failure of a success confirmation message in this Laravel 8 application?

I am working on an app with Laravel 8.

I use the following method to add new users to the users table:

public function insert() {

    //Check if user already exists
    $user = User::where('email', '=', session('userEmail'))->first();

    if (!$user) {
        return User::create([
            'first_name' => session('firstName'),
            'last_name' => session('lastName'),
            'email' => session('userEmail'),
            'role_id' => 1
        ]);
    }
    else {
        return redirect('/users')->with('error', 'User aleady exists!);
    }
} 

The problem:

I wanted to add a success confirmation message of "User created successfully". For this purpose, I did:

if (!$user) {
    return User::create([
        'first_name' => session('firstName'),
        'last_name' => session('lastName'),
        'email' => session('userEmail'),
        'role_id' => 1
    ])->with('success', 'User created successfully');
}

For a reason I have not been able to find out, this fails. With this message:

Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given, called in

What am I doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source