empty string from DB to null ??? if($var === null){ statement} - laravel

I im chechking DB if there is record. and if there is no recod i wanna make one. But i cant get NULL from DB i got empty string. how can i solve this?
public function chechk_slots(){
$character_id = Auth::user()->id;
$inv_user = DB::table("slots")->where('character_id', $character_id)->get();
return $inv_user?? null ;
}
and
public function to_inventary()
{
$a = "Is record";
$b = "there is no record";
$character_id = Auth::user()->id;
$inv_items = DB::table("items_chars")->where('character_id', $character_id)->get();
$user_profile = $this->show_profile();
$slot = $this->chechk_slots();
//dd($slot);
//DB::table("slots")->insert(['character_id' => $character_id]);
// dd($slot[0]->character_id);
if($slot === null){
dd($b);
DB::table("slots")->insert(['character_id' => $character_id]);
}
else{
dd($a);
}
//return view('inventary', compact('user_profile', 'inv_items'));
}
my table in DB pic
There is no record
if I dd($slot); i got this pic
so empty string !=null and cant get a record...How can i change this?

Issue #1 - Collection
You will get a collection even if it has no data.
$inv_user = DB::table("slots")->where('character_id', $character_id)->get();
Issue #2 - Null coalescing
It similar to the ternary operator, but will behave like isset on the lefthand operand instead of just using its boolean value.
$inv_user = DB::table("slots")->where('character_id', $character_id)->get();
return $inv_user ?? null;
$inv_user assigned Illuminate\Support\Collection.
Solution
Use count() and ternary operator.
public function chechk_slots(){
$character_id = Auth::id();
$inv_user = DB::table("slots")->where('character_id', $character_id)->count();
return $inv_user ?: null ;
}

I guess if you want to get null from the query just use first() instead of get() and return the result in one line
return DB::table("slots")->where('character_id', $character_id)->first();

Related

I can't add string to all value an array

I am new in developing ِAPi from laravel i need to insert path app into value an array
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','halls.hall_adress','halls.hall_details','price_hours','price_int','halls.hall_name','imagas.image_path')->where('halls.id',157)
->get();
$results=[];
foreach ($halls as $hall) {
$array=json_decode($hall->image_path,true);
if (is_array($array))
{
$hall->image_path = 'http://127.0.0.1:8000/Imaga_halls/'.$array;
}
array_push($results, $hall);
}
return response()->json($results);
}
the error is
ErrorException: Array to string conversion
$hall->image_path = 'http://127.0.0.1:8000/Imaga_halls/'.$array;
You are trying to concat an array to a string here.
After get() method on query builder, you will get the collection, so that you can use map() function to loop every hall object.
And concat prefix path with image:
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','halls.hall_adress','halls.hall_details','price_hours','price_int','halls.hall_name','imagas.image_path')
->where('halls.id',157)
->get();
$results = $halls->map(function($hall) {
$array = json_decode($hall->image_path, true);
$hall->image_path = collect($array)->map(function($image) {
return 'http://127.0.0.1:8000/Imaga_halls/'.$image;
})->toArray();
return $hall;
});
return response()->json($results);

Api Platform DTO object created by transformer is not getting persisted

Using Api Platform, I have a problem using an input class and its transformation.
The following documentation has been followed.
https://api-platform.com/docs/core/dto/#using-data-transfer-objects-dtos
After Data Transformer service executes transformation and returns an object of the correct class, the object that is picked up by api-platform appears to be empty, so it either fails validation, if validation is present, or persistence to the database fails - due its fields appear to be empty.
Here is a simplified code of DataTransformer service methods - it produces an object with hardcoded values:
public function transform($object, string $to, array $context = [])
{
$newCreativeElement = new CreativeElement();
$newCreativeElement->setKeyName("HARDCODED VALUE");
$newCreativeElement->setIntValue(42);
return $newCreativeElement;
}
public function supportsTransformation($object, string $to, array $context = []): bool
{
if ($object instanceof CreativeElement){
return false;
}
$result = CreativeElement::class === $to && null !== ($context['input']['class'] ?? null);
return $result;
}
Edit:
It's solved by 2.4 release.
Upgrade your composer.json and enjoy.
I have the same problem.
Something i tried is return for an array instead of an object transform method. It's working but not real solution.
it's appear that denormalizer is called 2 times : once for your transformer, and after to transform "CreativeElement" into "CreativeElement" by AbstractItemNormalizer
$context['api_denormalize'] = true;
$context['resource_class'] = $class;
$inputClass = $this->getInputClass($class, $context);
if (null !== $inputClass && null !== $dataTransformer = $this->getDataTransformer($data, $class, $context)) {
$data = $dataTransformer->transform(
parent::denormalize($data, $inputClass, $format, ['resource_class' => $inputClass] + $context),
$class,
$context
);
}
return parent::denormalize($data, $class, $format, $context);
Looking for solution too

Laravel 5.6 foreach not showing any data

I want to ask. I use foreach for showing my data from database. But nothing happen on view. Here is my code :
public function page($page_url = null){
if($page_url == "villas"){
$villa = Pages::where(['url_page' => $page_url])->first();
$postvilla = Posts::where(['id_page' => $villa->id_page]);
return view('front.villa', compact(array('villa', 'postvilla')));
}else if($page_url == "admin"){
return redirect('/admin/home');
}
}
You can pass variables in compact like
return view('front.villa', compact('villa', 'postvilla'));

Laravel 5.4 Collection Map Return Values

I'm having trouble creating a function on collection map with return values.
public function getCollectionFakeId($collection, $fieldNames){
$optimus = $this->optimus;
$result = $collection->map(function($item, $key) use ($optimus, $fieldNames) {
return [
$fieldNames[0] =>$optimus->encode($item->id),
$fieldNames[1] => $item->lastname
];
}) ;
dd($result);
return json_decode(json_encode($result), FALSE);
}
As you can see the return fieldNames[0] is being hardcoded. I don't know how many fieldNames it will received. I need to return those fieldnames with obfuscated Id. So basically The only changed is the Id. Here is the screenshot.
As you can see the fieldNames are just 2 but what if it becomes 5 or 6. I don't really know how many fieldNames they are going to pass in the parameter. How can I return it. Thanks.
In case someone will encounter this problem. Here is my solution...
public function getCollectionFakeId($collection, $fieldNames){
$optimus = $this->optimus;
$result = $collection->map(function($item, $key) use ($optimus, $fieldNames) {
$mapFieldNames = array_map(function($v) use ($optimus, $item) {
if( $v == 'id'){
return $optimus->encode($item->id);
}
else{
return $v;
}
}, $fieldNames);
return $mapFieldNames;
}) ;
dd($result);
return json_decode(json_encode($result), FALSE);
}
The result is the same. AWESOME!

Laravel 4 hasMany with WHERE clause

Not sure if this is the correct way to add an additional query to the hasMany argument but was unsuccessful. Is this possible?
public function menuItems($parent=false){
if($parent){
$menuItems = $this->hasMany('MenuItem')->where('parent',$parent);
}else{
$menuItems = $this->hasMany('MenuItem');
}
return $menuItems;
}
When called using
$menu_items = $menu->menuItems(0);
This just seems to return an empty array when passed a parent. Even though data with MenuItem->parent = 0 exists
Do I need to some way distinguish I'm asking for my linked items "parent" and not the main models "parent"
public function menuItems(){
return $this->hasMany('MenuItem');
}
Called with
$menu_items = $menu->menuItems()->where('parent', 0)->get();
I am not sure about the query part but at first wouldn't passing a 0 to the function still register the $parent variable as false? So maybe just check if the $parent is not null.
public function menuItems($parent = null){
if(!$parent == null)){
$menuItems = $this->hasMany('MenuItem')->where('parent',$parent);
}else{
$menuItems = $this->hasMany('MenuItem');
}
return $menuItems;
}
In PHP 0 = FALSE, change this
if( $parent ){
for this
if( $parent !== false ){

Resources