Hello , I am trying to bring the last data of my table but when I return I see that it brings it as an array type and it does not enter the validation, how could I solve this?
I attach the code:
$credentials=tbl_usuario::select('rol')->orderBy('usu_id')->take(1)->get();
//$credentials=DB::select('select rol from tbl_usuario order by usu_id desc limit 1')->get();
if ($credentials =='Lab Catálisis' or $credentials =='Lab Suelos' or $credentials =='Lab Biotecnología' or $credentials =='Lab Análisis petrofísicos') {
$lab = new tbl_lab();
$lab->lab_ceco = $request->ceco;
$lab->lab_direccion = $request->direccion;
$lab->lab_lider = $request->lider;
$lab->lab_usu_id = tbl_usuario::max('usu_id');
$lab->save();
return view('login');
}
return $credentials;
This is what the $credentials variable returns:
[{"rol":"Lab Cat\u00e1lisis"}]
To get the last element you will need other functions, besides it will always bring you an object even if it is just an element
You should get the latest record with
first
What is happening to you is that get() returns an array by itself and then you are comparing an array with a string, hence the error. Here are some examples so you know how the ORM works .
->get()
->find($id)
- >first()
->all()
->count()
These are examples of the most common but you also have variants of them such as:
That basically if it does not find what it is looking for it returns an exception. This can be interesting if you want to send the user to your custom 404 page.
All the examples are taken from the link that I leave you. Hope this can help you :)
The simplest thing in this case is to pass the value of the column that you want to retrieve between square brackets, that is,
So that from the returned collection only take the heat that corresponds to the key declared in quotes.
Or you change as they already told you to get for first and you can assign the access of said value to a property like this
And later use in your conditional to the property $value;
You can also drop using orderBy and instead apply latest which orders equal by taking the created_at column like so