Our Black Friday sale is now live! All individual subscriptions are 50% OFF. This week only!

mirsahib

mirsahib

Member Since 4 Months Ago

Experience Points
380
Total
Experience

4,620 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
380 XP
Jul
18
4 months ago
Activity icon

Replied to Add New Row To Model Table

Thanks @marianomoreyra I am using DB because i learn sql before eloquent and i am kind of lazy to learn the eloquent syntax. look like i have to change my habit

Activity icon

Started a new Conversation Add New Row To Model Table

I am try to insert new item to Payment table Here is my Payment table

public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('tenant_id')->unsigned();
            $table->integer('paid_rent')->default(0);
            $table->integer('dues')->default(0);
            $table->string('pay_month',15);
            $table->string('pay_year',5);
            $table->boolean('pay_status')->default(0);
            $table->string('comment')->default("Earum eligendi reprehenderit impedit eveniet. Omnis et optio voluptatem dolorum non.");
            $table->timestamps();
            $table->foreign('tenant_id')->references('id')->on('tenants');
        });
    }

Here is my controller function

public function create(Request $request){
        $validateData = Validator::make($request->all(),[
            'month'=>'required',
            'year'=>'required',
        ]);
        if($validateData->fails()){
            return response()->json(["message"=>$validateData->messages()], 404);
        }else{
            $tenantRows = DB::select(DB::raw("SELECT COUNT(tenants.id) FROM tenants WHERE tenants.tenant_status=:status"),array('status'=>1));
            $tenantsId = DB::select(DB::raw("SELECT tenants.id FROM tenants WHERE tenants.tenant_status=:status"),array('status'=>1));
            foreach($tenantsId as $id){
                $payment = new Payment;
                $payment->tenant_id = $id;
                $payment->pay_month = $request->month;
                $payment->pay_year = $request->year;
                $payment->save();                
            }
            return response()->json('success');
        }

    }

I am getting the following error while inserting new row to the table

Object of class stdClass could not be converted to string
Jul
17
4 months ago
Activity icon

Started a new Conversation BadMethodCallException : Model Function Doesn't Exist Even Though It Is There

I have 5 table but i am currently concern with 2 table Tenant and Payment, Tenant table has one to many relation with Payment table (Tenant table is also belongs to House table)

class Tenant extends Model
{
    //
    protected $fillable = ['name','nid','nid_img','phone','exp_rent','paid_rent',
                            'dues','pay_date','comment','status','exit_date'];


                            

    public function house()
    {
        return $this->belongsTo(House::class);
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }
}

Here is the seeder function

public function run()
    {
        factory(App\House::class, 10)->create()->each(function ($house) {
            // Seed the relation with one address
            $tenant = factory(App\Tenant::class,5)->make();
            $mother = factory(App\MotherMeter::class)->make();
            $sub_meter = factory(App\SubMeter::class)->make();
            $payment = factory(App\Payment::class,5)->make();
            $house->tenants()->saveMany($tenant);
            $house->motherMeter()->save($mother);
            $tenant->payments()->saveMany($payment);
            $mother->sub_meters()->save($sub_meter);
        });
    }

I am getting this error even though the function payments exists in the Tenant model

 BadMethodCallException 

  Method Illuminate\Database\Eloquent\Collection::payments does not exist.
Jul
14
4 months ago
Activity icon

Replied to Inserting Row With Foriegn Key

thanks i now know where is my mistake

Activity icon

Replied to Inserting Row With Foriegn Key

$request->house_id is ok

Even I have tried passing an integer value but that doesn't work

tenant->house_id = 110

Activity icon

Replied to Inserting Row With Foriegn Key

now it sending

 Trying to get property 'id' of non-object

i have tried

$tenant->house_id = $request->house_id

but this return

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`project-whirlpool`.`tenants`, CONSTRAINT `tenants_house_id_foreign` FOREIGN KEY (`house_id`) REFERENCES `houses` (`id`)) (SQL: insert into `tenants` (`name`, `nid`, `phone`, `reg_date`, `exp_rent`, `house_id`, `updated_at`, `created_at`) values (Mir, 2334, 234, 2020-07-08, 234, 110, 2020-07-14 14:22:17, 2020-07-14 14:22:17))
Activity icon

Started a new Conversation Inserting Row With Foriegn Key

I have two tables Tenant and House. here is my Tenant table migration file:


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTenantsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tenants', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name',50);
            $table->string('nid',50);
            $table->string('nid_img')->default("https://via.placeholder.com/150");
            $table->string('phone',50);
            $table->integer('exp_rent');
            $table->integer('paid_rent')->default(0);
            $table->integer('dues')->default(0);
            $table->date('reg_date');
            $table->date('pay_date')->default("2020-01-01");
            $table->string('comment')->default("Earum eligendi reprehenderit impedit eveniet. Omnis et optio voluptatem dolorum non.");
            $table->integer('house_id')->unsigned();
            $table->string('status',10)->default('NULL');
            $table->date('exit_date')->default('2020-01-01');
            $table->timestamps();

            $table->foreign('house_id')->references('id')->on('houses');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tenants');
    }
}

House table


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateHousesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('houses', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('hrid');
            $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('houses');
    }
}

TenantController


<?php

namespace App\Http\Controllers;

use App\Tenant;
use App\House;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;


class TenantController extends Controller
{
   
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        
        $validateData = Validator::make($request->all(),[
            'name'=>'required',
            'nid'=>'required',
            //'nid_img'=>'required',
            'phone'=>'required',
            'exp_rent'=>'required',
            'reg_date' =>'required',
            //'paid_rent'=>'required',
            //'dues'=>'required',
            //'pay_date'=>'required',
            //'comment'=>'required',
            'house_id'=>'required',
            //'status'=>'required',
            //'exit_date'=>'required',
        ]);
        if($validateData->fails()){
            return response()->json([
                'message'=>'Invalid input'
            ]);
        }else{
            $tenant = new Tenant;
            $house  = House::find($request->house_id);
            if($request->nid_img){
                $tenant->name = $request->name;
                $tenant->nid = $request->nid;
                $tenant->nid_img = $request->nid_img;
                $tenant->phone = $request->phone;
                $tenant->reg_date = $request->reg_date;
                $tenant->exp_rent = $request->exp_rent;
                //$tenant->house_id = $request->house_id;
                $tenant->house()->associate($house);

                $tenant->save();
                return response()->json([
                    'message'=>'Tenant Created Successfully','tenant'=>$tenant
                ]);
            }else{
                $tenant->name = $request->name;
                $tenant->nid = $request->nid;
                $tenant->phone = $request->phone;
                $tenant->reg_date = $request->reg_date;
                $tenant->exp_rent = $request->exp_rent;
                //$tenant->house_id = $request->house_id;
                $tenant->house()->associate($house);
                $tenant->save();
                return response()->json([
                    'message'=>'Tenant Created Successfully','tenant'=>$tenant
                ]);
            }
        }
    }
    
}

House Model

<?php

namespace App;

use App\Tenant;
use App\motherMeter;
use Illuminate\Database\Eloquent\Model;

class House extends Model
{
    //
    public function tenant(){
        return $this->hasOne(Tenant::class);
    }
    public function motherMeter(){
        return $this->hasOne(MotherMeter::class);
    }
}

Tenant model

<?php

namespace App;
use App\House;
use Illuminate\Database\Eloquent\Model;

class Tenant extends Model
{
    //
    protected $fillable = ['name','nid','nid_img','phone','exp_rent','paid_rent',
                            'dues','pay_date','comment','status','exit_date'];

    public function house()
    {
        return $this->belongsTo(House::class);
    }

    
}

I am getting this error while inserting a new Tenant

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'house_id' cannot be null (SQL: insert into `tenants` (`name`, `nid`, `phone`, `reg_date`, `exp_rent`, `house_id`, `updated_at`, `created_at`) values (Mir, 2334, 234, 2020-07-08, 234, ?, 2020-07-14 06:20:47, 2020-07-14 06:20:47))
Jul
02
4 months ago
Activity icon

Replied to How To Know What Is Inside An Eloquent Object

sorry i am using tinker which doesn't provide formatted text in the shell

Activity icon

Started a new Conversation How To Know What Is Inside An Eloquent Object

In Laravel eloquent documentation there is an example of user class

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

and below it says Dynamic properties allow you to access relationship methods as if they were properties defined on the model.

$phone = User::find(1)->phone;

my question is how to know what is inside the $phone variable (i know its an object but i want to know what are the attribute it has)

and please don't suggest var_dump,dd or ddd it's not helpful

Jun
30
4 months ago
Activity icon

Replied to Illuminate/Database/QueryException While Seeding The Database With Fake

I have added the column tenant_id to the Mother meter table but now i get the following error

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`project-whirlpool`.`mother_meters`, CONSTRAINT `mother_meters_assign_hrid_foreign` FOREIGN KEY (`assign_hrid`) REFERENCES `tenants` (`hrid`)) (SQL: insert into `mother_meters` (`meter_number`, `assign_hrid`, `type`, `consume_unit`, `bill_amount`, `year`, `month`, `pay_status`, `tenant_id`, `updated_at`, `created_at`) values (39180520, 63018042, Sub Meter, 109, 1586, 1970, 11, Paid, 1, 2020-07-01 07:24:06, 2020-07-01 07:24:06))

tenant model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\MotherMeter;

class Tenant extends Model
{
    //
    protected $fillable = ['name', 'nid','nid_img','phone','exp_rent','paid_rent','dues','pay_date','comment','hrid','status','exit'];

    public function mother_meter(){
        return $this->hasOne(MotherMeter::class);
    }

}

mother meter model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use SubMeter;

class MotherMeter extends Model
{
    //

    protected $fillable = ['tenant_id','meter_number','hrid','type','consume_unit','bill_amount','year','month','pay_status'];
    
    public function sub_meters(){
        return $this->hasMany(SubMeter::class);
    }
}

tenant table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTenantsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tenants', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('nid');
            $table->string('nid_img');
            $table->string('phone');
            $table->string('exp_rent');
            $table->string('paid_rent');
            $table->string('dues');
            $table->string('pay_date');
            $table->string('comment');
            $table->unsignedInteger('hrid')->index(); //home and room no
            $table->boolean('status');
            $table->date('exit');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tenants');
    }
}

Mother meter table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateMotherMetersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */

    //protected $fillable = ['meter_number','hrid','type','consume_unit','bill_amount','year','month','pay_status'];

    public function up()
    {
        Schema::create('mother_meters', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('tenant_id');
            $table->unsignedInteger('meter_number')->index();
            $table->unsignedInteger('assign_hrid')->index();//home or room no
            $table->string('type');
            $table->string('consume_unit');
            $table->string('bill_amount');
            $table->string('year');
            $table->string('month');
            $table->string('pay_status');
            $table->timestamps();
            $table->foreign('tenant_id')->references('id')->on('tenants');
            $table->foreign('assign_hrid')->references('hrid')->on('tenants');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('mother_meters');
    }
}

and in the image green text represent primary key and yellow text foreign key

Activity icon

Started a new Conversation Illuminate/Database/QueryException While Seeding The Database With Fake

I am getting the following error while seeding the database

Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tenant_id' in 'field list' (SQL: insert into `mother_meters` (`meter_number`, `assign_hrid`, `type`, `consume_unit`, `bill_amount`, `year`, `month`, `pay_status`, `tenant_id`, `updated_at`, `created_at`) values (05952960, 51751111, Sub Meter, 206, 2069, 1982, 05, Paid, 21, 2020-06-30 14:45:14, 2020-06-30 14:45:14))'

below is the model factory

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Model;
use Faker\Generator as Faker;


$factory->define(App\Tenant::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'nid' => $faker->ean13,
        'nid_img' => $faker->imageUrl($width = 640, $height = 480),
        'phone' => $faker->phoneNumber,
        'exp_rent' => $faker->numberBetween($min = 1000, $max = 3000),
        'paid_rent' => $faker->numberBetween($min = 1000, $max = 3000),
        'dues' => $faker->numberBetween($min = 1000, $max = 3000),
        'pay_date' => $faker->date($format = 'Y-m-d', $max = 'now'),
        'comment' =>$faker->text,
        'hrid' => $faker->ean8,
        'status' => $faker->boolean(1),
        'exit' => $faker->date($format = 'Y-m-d', $max = 'now'),

    ];
});

$factory->define(App\MotherMeter::class, function (Faker $faker) {
    return [
        //
        'meter_number'=>$faker->ean8,
        'assign_hrid'=>$faker->ean8,
        'type'=> $faker->randomElement(['Mother Meter','Sub Meter']),
        'consume_unit'=>$faker->numberBetween($min = 100, $max = 300),
        'bill_amount'=>$faker->numberBetween($min = 1000, $max = 3000),
        'year'=>$faker->year($max = 'now'),
        'month'=>$faker->month($max = 'now'),
        'pay_status'=>$faker->randomElement(['Paid','Not Paid'])

    ];
});
$factory->define(App\SubMeter::class, function (Faker $faker) {
    return [
        //
        'prev_reading'=>$faker->numberBetween($min = 1000, $max = 3000),
        'curr_reading'=>$faker->numberBetween($min = 3000, $max = 4000),
        'consume_unit'=>$faker->numberBetween($min = 100, $max = 300),
        'bill_amount'=>$faker->numberBetween($min = 2000, $max = 3000),
        'year'=>$faker->year($max = 'now'),
        'month'=>$faker->year($max = 'now'),
        'pay_status'=>$faker->randomElement(['Paid','Not Paid'])
    ];
});

Below is seeder factory class

<?php

use Illuminate\Database\Seeder;
use App\Tenant;
use App\MotherMeter;
use App\SubMeter;

class TenantSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
        factory(Tenant::class, 20)->create()->each(function($tenant){

            $mother_meter = factory(MotherMeter::class)->make();
            $tenant->mother_meter()->save($mother_meter);
            $sub_meter = factory(SubMeter::class)->make();
            $mother_meter->sub_meters()->saveMany($mother_meter);
        });
    }
}

Here is the relationship diagram

https://imgur.com/RhR5enY

Jun
29
4 months ago
Activity icon

Awarded Best Reply on Error While Making A Non Primary Key Foreign Key (errno: 150 "Foreign Key Constraint Is Incorrectly Formed)

Solved it with the following change

tenant table

$table->unsignedInteger('hrid')->index(); //home and room no

Mother meter table

$table->unsignedInteger('meter_number')->index();
$table->unsignedInteger('assign_hrid')->index();//home or room no

Activity icon

Replied to Error While Making A Non Primary Key Foreign Key (errno: 150 "Foreign Key Constraint Is Incorrectly Formed)

Solved it with the following change

tenant table

$table->unsignedInteger('hrid')->index(); //home and room no

Mother meter table

$table->unsignedInteger('meter_number')->index();
$table->unsignedInteger('assign_hrid')->index();//home or room no

Activity icon

Replied to Error While Making A Non Primary Key Foreign Key (errno: 150 "Foreign Key Constraint Is Incorrectly Formed)

i have made the change in tenant table same error and also try to migrate while making the same change in mother meter table same error

Activity icon

Started a new Conversation Error While Making A Non Primary Key Foreign Key (errno: 150 "Foreign Key Constraint Is Incorrectly Formed)

I have the following relationship diagram https://imgur.com/RhR5enY (green text means primary key and yellow text mean foreign key)

I am getting the following error while migration

errno: 150 "Foreign key constraint is incorrectly formed

Tenant Table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTenantsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tenants', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('nid');
            $table->string('nid_img');
            $table->string('phone');
            $table->string('exp_rent');
            $table->string('paid_rent');
            $table->string('dues');
            $table->string('pay_date');
            $table->string('comment');
            $table->integer('hrid'); //home and room no
            $table->boolean('status');
            $table->date('exit');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tenants');
    }
}

Mother Meter Table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateMotherMetersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */

    //protected $fillable = ['meter_number','hrid','type','consume_unit','bill_amount','year','month','pay_status'];

    public function up()
    {
        Schema::create('mother_meters', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('meter_number');
            $table->unsignedInteger('assign_hrid');//home or room no
            $table->string('type');
            $table->string('consume_unit');
            $table->string('bill_amount');
            $table->string('year');
            $table->string('month');
            $table->string('pay_status');
            $table->timestamps();


            $table->foreign('assign_hrid')->references('hrid')->on('tenants');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('mother_meters');
    }
}

Sub Meter Table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateSubMetersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */

    //protected $fillable = ['meter_number','hrid','type','prev_reading','curr_reading','consume_unit','bill_amount','year','month','pay_status'];

    public function up()
    {
        Schema::create('sub_meters', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('assign_meter_num');
            $table->unsignedInteger('rid');//home or room no
            $table->string('type');
            $table->string('prev_reading');
            $table->string('curr_reading');
            $table->string('consumeny_unit');
            $table->string('bill_amount');
            $table->string('year');
            $table->string('month');
            $table->string('pay_status');
            $table->timestamps();

            $table->foreign('assign_meter_num')->references('meter_number')->on('mother_meters');
            $table->foreign('rid')->references('assign_hrid')->on('mother_meters');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('sub_meters');
    }
}