How to call a model function inside the controller in Laravel 5
<?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()
.
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.