funguy
funguy

Reputation: 2160

How to resolve a controller with make parameter in laravel 5?

Previously I could do something like this:

/var/www/laravel/app/Http/Controllers/HelloController.php

<?php namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Hello\Hello as Hello;

class HelloController extends Controller {
    public function index() {

        $o = new Hello;

        $o = new Hello('changed1','changed1');

        var_dump($o);
    }
}

/var/www/laravel/app/Models/Hello

<?php namespace App\Models\Hello;

use Illuminate\Database\Eloquent\Model\Hello.php;


class Hello extends Model
{
    public function __construct($one='default1', $two='default2')
    {
        echo "First  Param: $one","\n<br>\n";
        echo "Second Param: $two","\n<br>\n";
        echo "\n<br>\n";
    }
}

routes.php

Route::get('tutorial', function() {
    $app = app(); 
    $app->make('Hello');
});

Instantiating without make works, but this now brings an error:

ReflectionException in Container.php line 776: Class Hello does not exist

What do you think I am missing in here?

Upvotes: 0

Views: 2766

Answers (1)

gpopoteur
gpopoteur

Reputation: 1519

Because your class has a namespace of App\Models\Hello, you must use the namespace of it when trying to instantiate the class. Therefore, your code should be like this:

Route::get('tutorial', function() {
    $app = app(); 
    $app->make('App\Models\Hello\Hello');
});

To expand a bit in the answer, you can remove the make() method call and just use the app() helper, and you'll end up with the same result:

Route::get('tutorial', function() {
    $app = app(); 
    $app->make('App\Models\Hello\Hello');

    // you can achieve the same with the
    // `app()` helper using less characters :)
    app('App\Models\Hello\Hello');
});

Upvotes: 4

Related Questions