user10459670
user10459670

Reputation:

Laravel : checking if a record ID is Exists

Sorry to ask, Im new to Laravel and i have a project that i working now. I want to check if Data ID is exists in my DB

So my problem : if Data ID is new i want to make new ID Number of the Data, then if there is more than one Data ID i want to make auto increment ID Number of the Data before. recently i used this code in store controller:

$data = FUP::where('id')->first();

$data = FUP::where('id')->first();
        $bln = date('M');
        $thn = date('Y');

        if($data === NULL){
            $no_usulan = '1'.'/UP/'.$bln.'/'.$thn;
        }else{
            $id = FUP::getId();
            foreach ($id as $value)
            $idlama = $value->id;
            $idbaru = $idlama + 1;
            $no_usulan = $idbaru.'/UP/'.$bln.'/'.$thn;
        }

for the first record Data is get in to if($data === NULL), but then for the second is get in to if($data === NULL) too not go to else code.

sorry if my explanation is bad to understand you guys.

Upvotes: 2

Views: 2833

Answers (2)

MxGutierrez
MxGutierrez

Reputation: 31

The following does the job

$data = FUP::find($id);

It's shorter than

$data = FUP::where('id', $id)->first();

and does the same thing. You could even do the following if you want to return 404 automatically in case it can't find any record that matches the given id

$data = FUP::findOrFail($id);

Upvotes: 1

Chinh Nguyen
Chinh Nguyen

Reputation: 1266

firstly, don't insert the id manually, leave that to database auto increment. And secondly, in your query

$data = FUP::where('id')->first();

you forgot to pass $id parameter to where query, like this:

$data = FUP::where('id', $id)->first();

Upvotes: 3

Related Questions