0

I'm trying to, from my controller, access a method in a model that is in another namespace and the only way I could do this was to make the method static. Is this the right way to do it, or is there any neater approach?

PagesController.php (controller):

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Helpers\ConnectedHost;


class PagesController extends Controller
{

    /* 
     * REMOVED CODE HERE FOR READABILITY 
     * Below is where I instantiate the "connectedHost"-object
     */
    $hosts[$hostKey] = new ConnectedHost($hostAttributes['ipv4'], $hostAttributes['mac']);
}

/* REMOVED CODE HERE FOR READABILITY AS WELL */

ConnectedHost.php (helper-file):

namespace App\Helpers;

class ConnectedHost
{
    public $ipv4, $mac;

    public function __construct($ipv4, $mac)
    {
        $this->ipv4 = $ipv4;
        $this->mac = $mac;
        // This is where I call the getName-function staticly,
        $this->name = \App\Host::getName();
    }
}

Host.php (model):

namespace App;

use Illuminate\Database\Eloquent\Model;

class Host extends Model
{
    // The method below is declared static
    public static function getName()
    {
        $name = 'wenzzzel';

        return $name;
    }
}
2
  • Please, provide a sample of your code. As an advise, check this guide to learn how to improve the quality of your questions: How to Ask Commented Jan 28, 2019 at 19:28
  • 1
    I've updated my question with samples from my code and some comments to further explain which parts I'm referring to in my question. Commented Jan 28, 2019 at 19:39

1 Answer 1

1

If you are directly accessing the method from model like

$data = \App\ModelName::methodName();

Then your method should be static.

if your method is not static you can access like,

$model = new \App\ModelName();
$data = $model->methodName();
Sign up to request clarification or add additional context in comments.

1 Comment

Turned out I just had'nt instantiated my model before trying to access it......... do I need to say that I'm new to this? Anyways, thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.