Im trying to test when a record is empty or not. Not sure why this isn't working. user_id is my FK. When there is no record I like it to show that it's empty and when it's added to show it's added. I'm manually adding removing a record to test it.
Migration
Schema::create('business_dashboards', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('business_name');
$table->string('website');
$table->timestamps();
});
Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class BusinessDashboard extends Model
{
use HasFactory;
protected $fillable = [
'business_name',
'website',
];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function userprofile()
{
return $this->belongsTo(User::class);
}
}
Controller
$businessDashboardUserId = BusinessDashboard::where('user_id', null)->first();
if ($businessDashboardUserId) {
dd('Is Null');
} else {
dd('Not Null');
}
CodePudding user response:
Try with whereNull()
and count()
for conditional
$businessDashboardUserId = BusinessDashboard::whereNull('user_id')->first();
if (!$businessDashboardUserId->count()) {
dd('Is Null');
} else {
dd('Not Null');
}
Or even nicer
if (!BusinessDashboard::whereNull('user_id')->exists()) {
dd('Is Null');
} else {
dd('Not Null');
}
CodePudding user response:
Typically one would use Eloquent relationships for this. Your current approach has problems, such as returning BusinessDashboard
instances that might be soft deleted, or not ignoring User
instances that might be soft deleted.
$businessDashboard = BusinessDashboard::whereDoesntHave('userprofile')->first();
Providing more code might help users understand what you're trying to accomplish, and be able to provide a more complete recommendation.