2

I want to use Model functions in view

My controller function code:

 $model = Tickets::find(1);
 View::make('view')->withModel($model);

 return view('index.search', ['tickets' => $result]);

My model code:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tickets extends Model
{
    public function someFunction() {
        echo 'hello world!';
    }
}

My view code:

{{ $model->someFunction() }}
1
  • 1
    import App\Model Commented Sep 17, 2017 at 8:44

4 Answers 4

7

You need to import your model like this:

use App\Tickets;

right after line with namespace so it should look something like this:

<?php

namespace App\Http\Controllers;

use App\Tickets;
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, this does not work ( still writes that such a class does not exist
@Ostap34PHP Well, but I assume you don't have Model class existing. Shouldn't you use Ticket class instead? Please look at edited answer
2

This should fix the issue:

use App\Models\Ticket;

For laravel 7:

use App\Tickets;

For laravel 8:

use App\Models\Ticket;

1 Comment

You have just copied the accepted answer without formatting the code.
1

Your model should be

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Tickets extends Model
{
    public function someFunction() {
        echo 'hello world!';
    }
}

And controller function should be

$model = Tickets::find(1);
 View::make('view')->withModel($model);

 return view('index.search', ['tickets' => $result]);

2 Comments

as I was told from the previous answers, one has to add to the model: use app\tickets;
Actually you don't have to add use app\tickets; to Model, you have to add it to controller. When you extends class Tickets to Model, it automatically gets the model. Secondly, you are writing plural in Class, its not good practice. Also first letter of Class name should be capital
1

To get this to work you will either have to use the full namespace:

$model = \App\Tickets::find(1);

Or add a use statement to the top of the controller:

use App\Tickets;

and load the model with:

$model = Tickets::find(1);

1 Comment

Sorry, this does not work ( still writes that such a class does not exist

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.