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

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.

Related

Error : "Trying to get property 'id' of non-object" with Foreign keys on Laravel8

I want to write a correct PostFactory for seed my DB with Laravel8
I follow the documentation on Laravel8 for make my Factory for seed my database
https://laravel.com/docs/8.x/seeding#using-model-factories
I have 3 Models :
Category.php
Post.php
User.php
I can seed my DB when i use this command :
php artisan db:seed --class=UserSeeder
php artisan db:seed --class=CategorySeeder
But i can't seed :
php artisan db:seed --class=PostSeeder
php artisan db:seed for seed all DB with one command
My PostSeeder :
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
\App\Models\Post::factory(50)->create();
}
}
My PostFactory :
public function definition()
{
return [
'title' => $this->faker->sentence(rand(5, 10)),
'content' => $this->faker->sentences(50, true),
'image' => 'https://via.placeholder.com/350/65' . rand(1, 100),
'created_at' => now(),
'updated_at' => now(),
'category_id' => Category::inRandomOrder()->first()->id,
'users_id' => User::inRandomOrder()->first()->id,
];
}
My PostFactory does'nt want to take my seed
I encounter this error :
PS C:\Users\Chris\Desktop\Laravel_Projects\Blog> php artisan db:seed
ErrorException
Trying to get property 'id' of non-object
at C:\Users\Chris\Desktop\Laravel_Projects\Blog\database\factories\
28▕ 'content' => $this->faker->sentences(50, true),
29▕ 'image' => 'https://via.placeholder.com/350/65'
30▕ 'created_at' => now(),
31▕ 'updated_at' => now(),
1 C:\Users\Chris\Desktop\Laravel_Projects\Blog\database\factories\PostFactory.php:32
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Trying to get property 'id' of non-object", "C:\Users\Chris\Desktop\Laravel_Projects\Blog\database\factories\PostFactory.php", [])
2 C:\Users\Chris\Desktop\Laravel_Projects\Blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\Factory.php:424
Database\Factories\PostFactory::definition()
My problem come with my 2 foreign keys :
I see the other post with this error but i can't debug with a dd();
I don't found how write my definition for my 2 foreign keys
I have try to check() my id but it'same result.
And to seed my posts_table after and before my users_table and catergories_table it's same.
I tried things with the different posts on the subject without success..Any help is appreciated.
Use the random id it is create random id and how many create record so you define in your seeder.this two line add on your post factory. i hope help you.
'category_id' => Category::all()->random()->id,
'users_id' => User::all()->random()->id,

Can I ignore specific migrations when running Laravel unit tests

When running tests in Laravel (php artisan test), I get an error 'duplicate column name: created_at'. This only occurs when i have field additions in the migrations directory. Am i able to ignore specific files when running Laravel tests? Or is there another way to get round this issue?
migrations:
if i just have this table, the tests work fine:
2021_06_18_134444_create_users_tables.php
after creating this migration, the tests fail:
2021_07_08_135544_add_timestamps_to_all_tables.php
a simple test:
use RefreshDatabase;
public function test_redirect_to_home_page_after_login()
{
$user = User::factory()->make([
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => bcrypt('123456')
]);
$response = $this->post('login', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
$response->assertRedirect('/');
$response->assertSessionHasErrors();
}

Unable to locate factory with name on production?

I create a factory of a model inside an artisan command:
public function handle()
{
if (!$this->isDevelopment()) {
$this->errorMessageSwitchEnvToDev();
return;
}
$userId = $this->ask('Please specifiy user_id you want to add the payouts to.',2148);
$numberOfPayouts = $this->ask('How many payouts you want to generate?', 10);
factory(\App\Payout::class, $numberOfPayouts)->create([
'user_id' => $userId,
]);
}
The artisan works on my local desktop, but it does not work after deployment on my test server.
I get the following error message:
InvalidArgumentException : Unable to locate factory with name [100] [App\Payout].
at /www/htdocs/w0146a6f/dev/dev4.partner.healyworld.net/releases/20201014150056/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:269
265| */
266| protected function getRawAttributes(array $attributes = [])
267| {
268| if (! isset($this->definitions[$this->class][$this->name])) {
> 269| throw new InvalidArgumentException("Unable to locate factory with name [{$this->name}] [{$this->class}].");
270| }
271|
272| $definition = call_user_func(
273| $this->definitions[$this->class][$this->name],
Exception trace:
1 Illuminate\Database\Eloquent\FactoryBuilder::getRawAttributes([])
/www/htdocs/w0146a6f/dev/dev4.partner.healyworld.net/releases/20201014150056/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:292
2 Illuminate\Database\Eloquent\FactoryBuilder::Illuminate\Database\Eloquent\{closure}()
/www/htdocs/w0146a6f/dev/dev4.partner.healyworld.net/releases/20201014150056/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php:122
I do the deployment with envoyer.
My factory is defined in database/factories/PayoutFactory.php
<?php
$factory->define(\App\Payout::class, function (Faker\Generator $faker) {
return [
'user_id' => function () {
return factory(App\User::class)->create()->id;
},
'amount' => $faker->randomFloat(2),
'req_amount' => 0,
'tax_amount' => 0,
'withheld' => 0,
'vat_rate' => $faker->randomNumber(2),
'released_amount' => $faker->randomFloat(2),
'released_amount_local_currency' => $faker->randomFloat(2),
'status' => 'released',
'flag' => 0,
'created_at' => $faker->dateTimeBetween('-6 months', 'now'),
];
});
However, it won't work on production. I already cleared the cache, the routes and called composer dump-autoload, but it still failes with the same issue.
Any suggestions?
I also read all answers of Laravel 5.2: Unable to locate factory with name [default] but none of them worked.
Notice this:
Unable to locate factory with name [100]
It looks like factory() is willing to use states instead of quantity. In this case it's looking for a factory state called (string) "100" instead of (int) 100
Cast your amount variable to be an integer
$numberOfPayouts = (int) $this->ask('How many payouts you want to generate?', 10);
Alternatively, try using ->times($amount) method to be more explicit.

Laravel DB Facade BadMethodCallException

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.

Laravel 5.1 factory definition unable to resolve closure for foreign relationships

I'm having trouble defining the factory function to handle foreign relationships for my business model. This is the code for my business model factory. The error message that I am getting is :
Uncaught exception 'ErrorException' with message 'Object of class
Closure could not be converted to string' in
/Users/patricia/Code/thank-views/vendor/laravel/framework/src/Illuminate/Database/Connection.php:390
Stack trace
It seems that it is unable to resolve the id for the user. When I run it in tinker it creates the model with a closure function for those fields. However I want to be able to generate these models to be used for my BusinessTest class. It's unable to resolve these dependencies. I'm not sure whether the best place to resolve these dependencies should be in the ModelFactory or elsewhere in the codebase.
$factory->define(App\Business::class, function (Faker\Generator $faker) {
return [
'slug' => $faker->word,
'name' => $faker->name,
'end_card' => $faker->word,
'white_label' => $faker->boolean,
'white_label_url' => $faker->word,
'payment_header' => $faker->word,
'payment_amount' => $faker->randomNumber(),
'payment_amount_display' => $faker->word,
'payment_cost' => $faker->randomNumber(),
'payment_activated' => $faker->boolean,
'main_user_id' => function () {
return factory(App\User::class)->create()->id;
},
];});
You can it change to:
'main_user_id' => $factory->create(\App\User::class)->id
or:
'main_user_id' => $faker->unique()->numberBetween($min = 1, $max = 50)
or:
'main_user_id' => $faker->unique()->randomDigit

Categories