find() and delete() not working in laravel 9 - laravel

find()
This is correct:
$user = Users::where('userid', '=', $id)->get();
return redirect('/register/view');
This is Incorrect:
$user = Users::find($id);
return redirect('/register/view');
delete()
This is Correct:
$user = Users::where('userid', '=', $id)->get();
if(!is_null($user))
{
Users::where('userid', '=', $id)->delete();
}
return redirect('/register/view');
This is Incorrect:
$user = Users::where('userid', '=', $id)->get();
if(!is_null($user))
{
$user->delete();
}
return redirect('/register/view');
Users Modedl:
class Users extends Model
{
use HasFactory;
protected $table = 'users';
protected $primarykey = 'userid';
}
Both codes are correct but not in my case. i don't know why. can anyone tell me what is wrong.

If you're looking for a single record by id (or userid in your case), don't use ->get():
$user = User::where('userid', $id)->first();
// OR
$user = User::find($id);
When deleting, also don't use ->get(). is_null on the result of ->get() will always be false, since ->get() returns a Collection, which isn't null.
$user = User::where('userid', $id)->delete();
// OR
$user = User::findOrFail($id)->delete();
Note: Your Model should be User, and the property to set the primary key in the Database is primaryKey, not primarykey:
class User extends Model {
use HasFactory;
protected $table = 'users';
protected $primaryKey = 'userid';
}
You're misunderstanding and misusing Laravel a lot here. ->get() should never be used for a single record, model names are singular, casing matters, etc etc.

Related

How to combine these multiple queries in laravel eloquent

I have the following query, where the final result I want is the $rate
// get latest effective date
$effectiveDate = CpfEffectiveDate::where('effective_from', '<=', $currentDate)
->orderBy("effective_from", 'DESC')
->first();
// get scheme related to the effective date and citizenship type
$scheme = CpfScheme::where("cpf_citizenship_id", $request->cpf_citizenship_id)
->where('cpf_effective_date_id', $effectiveDate->id)
->first();
// get rate based on scheme and other data
$rate = CpfRate::where("cpf_scheme_id", $scheme->id)
->where("minimum_wage", '<', ceil($totalWage)) // query does not accept floats. should be acceptable as wage tiers should be integers
->where("minimum_age", '<', $request->employee_age)
->orderBy('minimum_wage', 'DESC')
->orderBy('minimum_age', 'DESC')
->first();
How can I combine all 3 queries into a single one?
First I get the correct effective date from the first table, after which I use it to find the correct scheme (together with a citizenship_id) which I use to find the correct rate.
Here are the following models:
CpfRate
class CpfRate extends Model
{
protected $table = "cpf_rates";
protected $primaryKey = "id";
protected $hidden = ["created_at", "updated_at"];
public function scheme()
{
return $this->belongsTo(CpfScheme::class, "cpf_scheme_id");
}
protected $fillable = [
"minimum_age",
"minimum_wage",
"employer_percentage",
"employee_percentage",
"employee_offset_amount", // used for special cases, such as -500 for percentage = 0.15 * (TW - 500)
"ordinary_wage_cap", // ordinary wage cap
];
}
CpfScheme
class CpfScheme extends Model
{
protected $table = "cpf_schemes";
protected $primaryKey = "id";
protected $hidden = ["created_at", "updated_at"];
public function citizenship()
{
return $this->belongsTo(CpfCitizenship::class, "cpf_citizenship_id");
}
public function effectiveDate()
{
return $this->belongsTo(CpfEffectiveDate::class, "cpf_effective_date_id");
}
}
CpfEffectiveDate
class CpfEffectiveDate extends Model
{
protected $table = "cpf_effective_dates";
protected $primaryKey = "id";
protected $hidden = ["created_at", "updated_at"];
// mutated to dates
protected $dates = ['effective_from'];
public function schemes() {
return $this->hasMany(CpfScheme::class, "cpf_effective_date_id");
}
}
CpfCitizenship
class CpfCitizenship extends Model
{
protected $table = "cpf_citizenships";
protected $primaryKey = "id";
protected $hidden = ["created_at", "updated_at"];
// fields
protected $fillable = ['description'];
public function schemes() {
return $this->hasMany(CpfScheme::class, "cpf_citizenship_id");
}
}
$rate = CpfRate::select('cpf_rates.*')
->where('cpf_scheme_id', '=', function ($query) use ($request) {
$query->select('id')
->from('cpf_schemes')
->where("cpf_citizenship_id", $request->cpf_citizenship_id)
->where('cpf_effective_date_id', '=', function($query, $currentDate) {
$query->select('id')
->from('cpf_effective_dates')
->where('effective_from', '<=', $currentDate)
->orderBy("effective_from", 'DESC')
->limit(1);
})
->first();
})
->where("minimum_wage", '<', ceil($totalWage)) // query does not accept floats. should be acceptable as wage tiers should be integers
->where("minimum_age", '<', $request->employee_age)
->orderBy('minimum_wage', 'DESC')
->orderBy('minimum_age', 'DESC')
->first();
I did not tested but what only here can be problem is $currentdate, so if it is problem just use Carbon class to get current date directly in query.

Laravel relationship many to many filtering on pivot field

I have a relationship between Invoice and Shift.
Invoice model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'user_id',
'date_ins',
'closeco',
'closedrh',
'lvl',
'new',
];
public function user()
{
return $this->hasOne(User::class,'id','user_id');
}
/**
* The roles that belong to the invoice.
*/
public function shifts()
{
return $this->belongsToMany(Shift::class, 'invoice_shift')
->withPivot([
'invoice_id', 'shift_id', 'shift_taken_id', 'shift_swapped_date', 'shift_taken_date', 'tas',
'status_tas', 'status_co', 'status_drh', 'back_co',
'msg', 'msg_co', 'msg_drh'
])
->orderBy('status_drh', 'ASC')
->orderBy('status_co', 'ASC');
}
}
Shift model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shift extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'code',
'description',
];
/**
* The users that belong to the role.
*/
public function invoices()
{
return $this->belongsToMany(Invoice::class, 'invoice_shift')
->orderBy('status_drh', 'ASC')
->orderBy('status_co', 'ASC');
}
}
So I have a pivot table called Invoice_shift.
I cannot extract, starting from invoices table, just invoices that have tas (in invoice_shift table) = current logged user.
I cannot filter as a static value in Invoice model definition with wherepivot because it is dynamic value, every time logged user id is different.
I tried to do this in controller
$invoices = Invoice::with('shifts.invoices')
->orderBy('date_ins', 'DESC')->get();
$filter = $invoices->shifts()
->wherePivot('tas', '=', $user_id)
->get();
but I get an error because I think invoices are a collection ... I tried to insert a foreach...but it doesn't work.
The error message:
Method Illuminate\Database\Eloquent\Collection::shifts does not exist
How can I do this?
Thanks
$invoices is an instance of Illuminate\Database\Eloquent\Collection and therefore relationship shifts() cannot be used..
Maybe you need the correct Eloquent builder to filter invoices using whereHas("relationship", fn)
$filteredInvoices = Invoice::with('shifts.invoices')
->whereHas("shifts", function($query) use ($user_id) {
$query->wherePivot('tas', $user_id)
})
->orderBy('date_ins', 'DESC')
->get();

Soft delete in laravel is not hiding record in view

I am using Eloquent soft delete to delete a row in the database. I use function destroy, in database column deleted_at have a date, but this is not hiding deleted records in view.
My code in controller.
$query = Role::join('users', 'roles.id', '=','users.role_id');
$user = User::all();
$users = $query->select('users.*','roles.name as role_name')->paginate(10);
My code in User Model
use SoftDeletes;
use HasFactory;
protected $table = 'users';
protected $guarded = [];
protected $hidden = [
'password', 'remember_token', 'deleted_at'
];
public function roles() {
return $this->belongsTo(Role::class);
}
My code in Models Role
use HasFactory;
protected $table = 'roles';
protected $guarded = [];
public function users() {
return $this->hasMany(User::class);
}
So it seems, the problem here is the join. Soft delete is an Eloquent feature which works on the model itself but not on the joined table. In case you have to join two tables, you have to query yourself to drop out the deleted column. In your case you can do it like
$query = Role::join('users', 'roles.id', '=', 'users.role_id');
$user = User::all();
$users = $query->select('users.*', 'roles.name as role_name')->where('users.deleted_at', null)->paginate(10);
so this will drop out the deleted column. but as you are using relationship, why you have to join yourself?? the relationship will handle that for you. you can simply call like
$roles = Role::with('users')->get();
and you can get every users of a role like
foreach ($roles as $role) {
foreach ($role->users as $user) {
echo $user->attribute;
}
}
and a note for you. you need to pass the foreign key name as the second parameter of the relationship definition as it's not matching the laravel's naming convention.
public function roles() {
return $this->belongsTo(Role::class, 'role_id');
}
and
public function users() {
return $this->hasMany(User::class, 'role_id');
}
if you used eloquent relationship it would worked but now you are using join. the login of eloquent orm is this, you can write your SQL and query it but you have to manually select which do you want or not want(in this case you dont want the records that deleted_at column is filled. but if you use relationships you can have the benefits of soft delete and many other features.

Getting specific value when using eloquent from Laravel

I am using Laravel 5.2 and I need to get specific values from the database with a leftjoin. The code I am using is as follow:
public function commentList(Request $request)
{
$inputs = $request->all();
$commentList = Comment::select(
'projects_comments.id as comment_id',
'u.name as user_name',
'projects_comments.comment as comment',
'projects_comments.created_at as created_at'
);
$commentList->leftjoin('users AS u', 'projects_comments.user_id', '=', 'u.id');
if (!empty($inputs['project_ids'])) {
$commentList->where(function ($query) use ($inputs) {
foreach ($inputs['project_ids'] as $i) {
$query->orWhere('projects_comments.project_id', $i);
}
});
};
$data = $commentList->get();
return $data;
}
It works fine but I would like to know if there is a better way to do this using eloquent but I can't really understand how to write this for eloquent to work. I need to get all the comments from an array of project ids.
I have the following model for Comment:
class Comment extends Model
{
protected $table = 'projects_comments';
public $timestamps = true;
protected $guarded = ['id'];
public function project()
{
return $this->belongsTo('App\Project', 'project_id');
}
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
}
I assume what you want is to get Comments (with their users) that belongs to specific Projects provided by the user as an array of IDS
Comment::whereIn('project_id', $inputs['project_ids'])->with('user')->get();
And if you only want the id and name of the user associated with the comment, pass the fields to the with function like so
Comment::whereIn('project_id', $inputs['project_ids'])
->with('user:id,name')->get();

Need to take a sample of all positions where user_id is not equal to ours

Have 3 tables
users
posts
post_user (id, post_id, user_id)
class Post extends Eloquent {
protected $table = 'posts';
public $timestamps = true;
public function users()
{
return $this->belongsToMany('User');
}
}
class Users extends Eloquent {
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
public function posts()
{
return $this->belongsToMany('Post');
}
}
Controller
public function application()
{
$posts = Post::find(1);
$user = DB::table('post_user')->where('user_id', '=', $this->id)->lists('user_id');
$posts = Post::whereNotIn('id', $user)->get();
return View::make('applications')->with(array('posts' => $posts));
}
What am I doing wrong? If possible with an explanation
You probably want to do lists('post_id').
However there is a much nicer way with whereDoesntHave:
$userId = $this->id;
$posts = Post::whereDoesntHave('users', function($q) use ($userId){
$q->where('user_id', $userId);
})->get();
Assuming that $this->id contains your user id, try this:
$posts = Post::whereHas('users', function($q) {
$q->whereNotIn( 'id', [$this->id])
})->get();
Method whereHas() selects posts belonging users, which have met a condition within the Closure. And this condition - method whereNotIn() - check if user id is different form $this->id.

Resources