Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

adnan483's avatar

If exist take id if not create new client

Hi, I'm looking solution for my problem, I need to get clients from database while typing(to pick up right one), and if client doesn't exist must create new one, if exist only take his user id and put it in order.

0 likes
3 replies
Snapey's avatar

you have to write it then if it does not work come and ask questions

If you dont know where to start follow some tutorials

Sodium's avatar

I would advice against that.

I ran into something like this in my collegue's code and it wasn't pleasant to understand what was going on.

Having proper routes to add and edit element and proper error messages when trying to access a ressource that doesn't exist helps keeping a cleaner code with short methods that do one single thing and do it well.

When a controller action starts by making some verifications and ends up doing different things based on that verification's result, you have started making a mess that will only get bigger as the application evolves.

Think of your co-workers or future co-workers. If they try to find where in your application you are creating new ressources, they will most likely start by searching for a route containing the word "add" or "create" and the corresponding controller action.

xmarks's avatar
xmarks
Best Answer
Level 8

You can do this:

  • Use Select2 to build a Search-Form. You can check This Tutorial.
  • While you type, the Database will be searched for a Client, which you can select and Submit, so you can for example, be taken to the Client's Page
  • If nothing is found, Select2 has an option to select what you have typed anyhow

You can then create other Routes and Controller, which will try to find the Client-ID (id would be same as name for the case where Client is not found but you selected it anyway). So the Controller would either:

  • Redirect to Client Page, if Client is found
  • Redirect to Client Creation Form, if Client is not Found

In case you are dealing with a new Client, you would redirect to a New Route, where you would create this new Client, and the Client Name could be auto-filled. You would then fill the other data, and finalize the creation of the Client.

1 like

Please or to participate in this conversation.