Laravel DB Facade BadMethodCallException - php

I'm trying to implement insertOrIgnore method from the Laravel DB Facade,
here's a link to the docs + explanation snippet:
https://laravel.com/docs/5.8/queries#inserts
The insertOrIgnore method will ignore duplicate record errors while
inserting records into the database:
DB::table('users')->insertOrIgnore([
['id' => 1, 'email' => 'taylor#example.com'],
['id' => 2, 'email' => 'dayle#example.com']
]);
And here's the piece of code that produces the error (it works with regular insert())
if ($datetime->format('H:i') >= '05:50' && $datetime->format('H:i') <= '07:10') {
DB::table('attendanceTable')->insertOrIgnore(['user_id' => $request->loggedUserId, 'day' => $datetime, 'shift_id' => $Shifts->id, 'created_at' => $datetime, 'updated_at' => $datetime]);
Here's the error that Laravel's Telescope produces
Call to undefined method Illuminate\Database\Query\Builder::insertOrIgnore()
Can someone point out what i'm doing wrong, or atleast give me a hint? Thanks in advance!

I had the same error, and it turned out to be because I was on laravel version 5.8.32, and insertOrIgnore was added in version 5.8.33.
Running composer update resolved the issue.

Related

DB::transaction is not working as exptected (Laravel)

i have 3 sql operations which i thought put them in transaction would be a good practice because many times I faced some issues like first query runs and another fails so this is my code below
DB::beginTransaction();
try {
//update loan application
$loanApplication->status = 'DISBURSED';
$loanApplication->tenure = $offerDetails['tenure'];
$loanApplication->amount_offered = $offerDetails['loanAmount'];
$isUpdated = $loanApplication->update();
//create loan disbursal
LoanDisbursal::insertGetId([
'created_dt' => Carbon::now(),
'user_id' => $loanApplication->user_id,
'loan_account' => $loanApplication->application_id,
'gateway_alias' => $this->gatewayAlias,
'amount_approved' => $tradeLineInfo['loanAmount'],
'amount_disbursed' => $tradeLineInfo['disbursalAmount'],
'disbursed_on' => $tradeLineInfo['disbursalDate'],
'disbursal_ref' => $tradeLineInfo['disbursalId'],
'tenure' => $offerDetails['tenure'],
'wallet_credit_status' => 'DISBURSED',
]);
//create loan profile account
ProfilesHasAccount::insertGetId([
'user_id' => $loanApplication->user_id,
'gateway' => $this->gatewayAlias,
'account_segment' => 'BUSINESS',
'1account_type' => 'LOAN',
'created_dt' => Carbon::now(),
'status' => 'ACTIVE',
]);
} catch (\Throwable $th) {
dd(DB::rollback());
dd($th);
}
DB::commit();
Now here is the problem ,
while doing this operation my loan applicatiob got updated but there was problem on loanDisbursal entry so my catch block was invoked ,
there I used DB::rollback ,
so according to rollback,
loanApplication status should have change as it was earlier but it is 'DISBURSED' and no rollback happened in simple words
Also I have another project setup in my system in which everything is working as expected so what maybe the cause for this ,
I guess anything related to mysql configuration?
so I am just thinking why this happened ?
any ideas or suggestions , would be very helpful
OKAY I found the answer and the problem was my projects contains multiple datbases so I just had to show connections on transactions like this
DB::connection('ipay_app_loans__write')->beginTransaction();
DB::connection('ipay_app_loans__write')->rollBack();
DB::connection('ipay_app_loans__write')->commit();
That's it!!

Trying to get property 'id' of non-object Laravel error

I am working on someone else code in a Project and when I try to run the php artisan migrate I am encountering an error!
class SeedAdminUser extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
// seed admin user
$admin = User::create([
'name' => 'Admin',
'email' => 'admin#admin.se',
'password' => Hash::make('password'),
'plan_id' => null,
]);
$admin->assignRole(['administrator', 'company']);
$plan = Plan::find(1);
Subscription::create([
'user_id' => 1,
'plan_id' => $plan->id,
'starts_at' => Carbon::now(),
'ends_at' => $plan->interval == 'monthly' ? Carbon::now()->addMonth() : Carbon::now()->addMonths(12),
]);
}
I am getting an error because of this line 'plan_id' => $plan->id,
Here is the Error message -
ErrorException
Trying to get property 'id' of non-object
at database/migrations/2021_06_04_055759_seed_admin_user.php:34
30|
31| $plan = Plan::find(1);
32| Subscription::create([
33| 'user_id' => 1,
> 34| 'plan_id' => $plan->id,
35| 'starts_at' => Carbon::now(),
36| 'ends_at' => $plan->interval == 'monthly' ? Carbon::now()->addMonth() : Carbon::now()->addMonths(12),
37| ]);
38| }
1 database/migrations/2021_06_04_055759_seed_admin_user.php:34
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Trying to get property 'id' of non-object", "/Applications/MAMP/htdocs/iSurvey/database/migrations/2021_06_04_055759_seed_admin_user.php", [Object(App\User)])
+21 vendor frames
23 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
Any Idea what is wrong with that line 'plan_id' => $plan->id, and how to fix it
This is because there is no records in plan model,
First check if records exists in plan model
dd($plan);
or
$plan = $plan ? $plan->id : '';
The problem is exactly what the error says. $plan is not an object, so trying to access a propriety on it result in an error.
Why is $plan not an object? Because Plan::find(1); cannot find a plan with an id of 1. $plan is probably null so you're effectively running null->id.
Since you're running migrations, you might want to make sure this code runs after your plans table is populated. I would give it a shot with php artisan migrate:fresh --seed (warning: this will empty your db tables and then repopulate them with migrations/seeders) or seeding in general.
Consider also using findOrFail instead of find to throw an exeception if the model is not found, since your subsequent code in this example depends on the model being found.
Make sure your plans are seeded before this migration runs. It's safer to use findOrFail instead. This way, you'll know the instant a plan isn't found.

CakePHP ""_joinData" is missing from the belongsToMany results" Error

I am currently in the process of updating old projects from cakephp 3.1.3 to 3.7.4.
For one of the projects I got the error
"_joinData" is missing from the belongsToMany results
I was unable to find any explanation to that specific error and since I am relatively new to PHP and CakePHP. and usually don't do much with databases I am currently a littlebit stuck despite lot's of information's about associations and CakePHP tables in general.
The error happens after an first() call on an model, like
$foundInstances = $instances->find()
->where([
'type_id' => $instanceTypeId,
'id' => $this->otherModel->id
])
->contain(['Features'])
->enableHydration(false);
$this->instances->first()
In the model class the relationsa re simply set like this:
$this->belongsToMany('BackendFeatures', [
'setForeignKey' => 'instance_id',
'setTargetForeignKey' => 'backend_feature_id',
'joinTable' => 'backend_features_instances'
]);
$this->belongsToMany('Features', [
'setForeignKey' => 'instance_id',
'setTargetForeignKey' => 'feature_id',
'joinTable' => 'features_instances'
]);
Can someone maybe give me an hint what i have to be looking for?

Factories on Laravel 5.2 not working as expected

I have a very strange problem with Laravel 5.2 factories.
I have recently upgraded from Laravel 5.1 to 5.2 following the upgrade guide on the Laravel website. All works as exepected except one factory. Yes the others work ok. Here are two of the factories:
$factory->define(App\Client::class, function (Faker\Generator $faker) {
return [
'name' => $faker->company,
'building' => $faker->buildingNumber,
'street' => $faker->streetName,
'town' => $faker->city,
'postcode' => $faker->postcode,
'country' => 'UK',
'telephone' => $faker->phoneNumber,
'fax' => $faker->phoneNumber,
];
});
$factory->define(App\Shift::class, function (Faker\Generator $faker) {
return [
'client_id' => $faker->numberBetween($min = 1, $max = 15),
'user_id' => $faker->numberBetween($min = 1, $max = 15),
'start' => $faker->dateTimeBetween($startDate='now', $endDate='+60 days'),
'public' => $faker->boolean(),
];
});
The top factory works no problem but the second one doesn't run at all cause my db seed to throw an error because its not populating the client_id which is a foreign key.
The only difference between the two models is that the client model doesn't use timestamps where as the shift model does. Other than that they are identical.
I will keep plugging away but any help to shed light on this would be greatly received.
When you add your own constructor, are you making sure to call parent::__construct() inside it?

A four digit year could not be found Data missing

I'm trying to seed using factories in Laravel 5.2
My code dies in the User factory:
$factory->define(App\User::class, function (Faker\Generator $faker) {
$countries = Countries::all()->pluck('id')->toArray();
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => bcrypt(str_random(10)),
'grade_id' => $faker->numberBetween(1, 5),
'country_id' => $faker->randomElement($countries),
'city' => $faker->city,
'latitude' => $faker->latitude,
'longitude' => $faker->longitude,
'role_id' => $faker->numberBetween(1, 3),
'verified' => true,
'remember_token' => str_random(10),
'provider' => '',
'provider_id' => str_random(5)
];
});
Giving me this error:
A four digit year could not be found Data missing
I found the cause, but don't know how to fix it.
When I call the factory, I call it like that:
factory(User::class)->create(['role_id',2]);
If I call it like that:
factory(User::class)->create();
I get no more error.
But I really need to seed different kind of users...
Any idea???
have you tried using key value array in the create method:
factory(User::class)->create(['role_id' => 2]);
I might be late to the party, I was having the same problem and it turns out its because I provided a key without a value in the array returned.
get rid of 'provider' => ''.
As to the cause of the problem i really don't know but it has something to do with Carbon
I had the same issue when using mass assignment and it turned I had forgotten to wrap my array of inputs in the request helper function
That is I had
Model::create([form inputs]);
Instead of
Model::create(request([form inputs]);
Just incase someone comes across it.
I recently encounter the same problem, lately I found out that the only problem is I put an invalid value to the timestamp column type.
In my case I have column email_verified_at [timestamp]. I miss understood I put a string like company#example.com instead of date values, it should be now().

Categories