I have been facing a problem of not able to use the model inside the controller in the new laravel framework version 5. i created the model using the artisan command "php artisan make:model Authentication" and it created the model successfully inside the app folder, after that i have created a small function test in it, and my model code looks like this.
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function test(){
echo "This is a test function";
}
}
Now i have no idea, that how shall i call the function test() of model to my controller , Any help would be appreciated, Thanks in advance.
To call the model method on an object created by the new keyword on user model you have to include user model in your controller file by using the use keyword like use App\Models\UserModel;.
$varbl = App::make("ControllerName")->FunctionName($params); to call a controller function from a my balde template(view page).
A quick and dirty way to run that function and see the output would be to edit app\Http\routes.php
and add:
use App\Authentication;
Route::get('authentication/test', function(){
$auth = new Authentication();
return $auth->test();
});
Then visit your site and go to this path: /authentication/test
The first argument to Route::get() sets the path and the second argument says what to do when that path is called.
If you wanted to take this further, I would recommend creating a controller and replacing that anonymous function with a reference to a method on the controller. In this case, you would change app\Http\Routes.php
by instead adding:
Route::get('authentication/test', 'AuthenticationController@test');
And then use artisan to make a controller called AuthenticationController
or create app\Http\Controllers\AuthenticationController.php
and edit it like so:
<?php namespace App\Http\Controllers;
use App\Authentication;
class AuthenticationController extends Controller {
public function test()
{
$auth = new Authentication();
return $auth->test();
}
}
Again, you can see the results by going to /authentication/test
on your Laravel site.
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function scopeTest(){
echo "This is a test function";
}
}
Just prefix test()
with scope
. This will become scopeTest()
.
Now you can call it from anywhere like Authentication::Test()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With