I
I
Ivan2020-08-18 21:03:34
Laravel
Ivan, 2020-08-18 21:03:34

How to return a model, but not write to the database using the firstOrNew, firstOrCreate or similar methods?

Good evening. Roughly speaking, there is something like this code.

public function GenerateUser($first_name,  $last_name)
    {
        $isset = User::where('first_name', $first_name)
            ->where('last_name', $last_name)->first();
        $response = null;
        if (isset($isset)) {
            $response = User::where('first_name', $first_name)
                ->where('last_name', $last_name)->first();
        } else {
            $response = new User();
            $response->first_name = $first_name;
            $response->last_name = $last_name;
            $response->save();
        }
        return response()->json($response);
    }


Should work as follows. 2 parameters come, we check in the database in the users table whether there is already such a user there. If there is, we return the model, we do not write anything to the database. If not, we return the model and write it to the database. This piece of code works fine, but you need to do something with the above methods to reduce the whole thing and increase readability. Tried everything, like this

public function GenerateUser($first_name, $last_name)
    {
        $response = User::firstOrNew([
                'first_name' => $first_name,
                'last_name' => $last_name,
            ]);
        $response->save();
        return response()->json($response);
    }

Returns the model, but also writes to the database whether there is such an entry there or not. Doesn't save without save(). Tried other similar methods, the result is about the same. How to solve it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2020-08-18
@Djonson86

Well, firstOrCreate, no? returns, or creates and returns

public function GenerateUser($first_name, $last_name)
{
  $user = User::firstOrCreate([
    'first_name' => $first_name,
    'last_name' => $last_name,
  ]);

  return response()->json($user);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question