Srinivasulu Rao Srinivasulu Rao - 2 months ago 65
PHP Question

How to call a model function inside the controller in Laravel 5

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.


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.