trzew
trzew

Reputation: 445

Laravel equivalent if statement

I am beginner php developer. I make my project in Laravel 8.

I have this migrations:

Schema::create('clients', function (Blueprint $table) {
    $table->id();
    $table->string('email');
    $table->integer('type')->comment('1 - Client individual , 2 - Client Company');
    $table->string('crm_number')->unique();
    $table->string('password');
    $table->string('verify_token');
    $table->rememberToken();
    $table->timestamp('password_assigned_at')->nullable();
    $table->timestamp('email_verified_at')->nullable();
    $table->timestamps();
    $table->deactivation();
    $table->softDeletes();

    $table->unique(['email', 'deleted_at']);
});

Schema::create('client_infos', function (Blueprint $table) {
    $table->id();
    $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
    $table->string('first_name');
    $table->string('last_name');
    $table->string('phone_nr')->nullable();
    $table->timestamps();
});

Schema::create('client_company_infos', function (Blueprint $table) {
    $table->id();
    $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
    $table->string('name');
    $table->string('nip')->nullable();
    $table->string('phone_nr')->nullable();
    $table->string('contact_email')->nullable();
    $table->string('invoice_email')->nullable();
    $table->timestamps();
});

If client.type = 1 - Client individual , 2 - Client Company

I have this code:

Client::leftJoin('client_company_infos', 'client_company_infos.client_id', '=', 'clients.id')
    ->leftJoin('client_infos', 'client_infos.client_id', '=', 'clients.id')
    ->select('clients.*',
        'client_company_infos.name as name',
        'client_infos.first_name as first_name',
        'client_infos.last_name as last_name',
    );

In my situation I have name - for company name, first_name for first name and last_name as last_name.

I need always one value "name":

  1. company = name
  2. individual user = name as 'first name + last name'

How can I make it?

Please help me

Upvotes: 0

Views: 66

Answers (1)

you can use the accessor for that, for example


class YourModel extend Model
{
   //foo bla bla

  public function getFullNameAttribute()
  {
     return sprintf('%s %s',$this->name,$this->lastname;
  }
}

using


User::find(63);

echo $user->full_name;

relevent document

Upvotes: 1

Related Questions