Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

DrPrez said:

I believe you can only use $table without $this->

Then the debugger screams:

Undefined variable: table
Last updated 1 year ago.
0

$table is an instance variable, not a static variable, so you can't use it in a static function (basic PHP).

Last updated 1 year ago.
0

thepsion5 said:

$table is an instance variable, not a static variable, so you can't use it in a static function (basic PHP).

So what's the solution? Is it impossible to add variables to a model in Laravel?

If i remove the "static" from the method it looks like this

public function getCustomers()

but then Laravel again screams

Non-static method Vorlauf::getCustomers() should not be called statically, assuming $this from incompatible context

Thanks, Sharping

Last updated 1 year ago.
0

You could try and define $table as a static variable. Or could use something like this:

public function getDistinctCustomerNames()
{
    $customer = new Customer;
    return DB::select("SELECT DISTINCT customer FROM ".$customer->table." ORDER BY customer ASC");
}
Last updated 1 year ago.
0

No chance! :-( This only happens if the class extends Eloquent...

If i put the method directly into the Controller it works.

Last updated 1 year ago.
0

Is this really so complicated?

I just want to define $table once "in the header" to use it in several methods of the Model (without hardcoding the table name everytime inside the query):

<?php

class CustomerModel extends Eloquent {

public $table = 'customers';
public $timestamps = false;

public static function getCustomers(){return DB::select("SELECT * FROM ".$this->table);}
public static function getSomething(){return DB::select("SELECT * FROM ".$this->table);}
public static function getCities(){return DB::select("SELECT * FROM ".$this->table);}
 
}
Last updated 1 year ago.
0

DrPrez said:

Sorry my bad, correct way is...


public static $variable = 'value';

public static function whatever()
{
   dd(self::$variable);
}

That's what I meant when I suggested that Sharping declare $table as a static variable.

Last updated 1 year ago.

voronovigor liked this reply

1

Sign in to participate in this thread!

Eventy

Your banner here too?

Sharping sharping Joined 28 Jun 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.