How do you reference a model in a laravel controller? [duplicate] - laravel-5

This question already has answers here:
Troubleshooting referencing a model in a laravel controller
(2 answers)
Closed 6 years ago.
I'm finding the distinction between "Controller" and "Model" in laravel 5.2 to be very blurry.
I use artisan to create a RESTful controller, and in the store method, I try to create a new object.
// store in the database
$car = new App\Models\CarModel;
Then I get the error as follows:
Class 'carfreak\Http\Controllers\App\Models\CarModel' not found
So it all seems to come down to the namespace of the controller, but I don't understand it.
The name space describes the controller, right?
So why is my reference the model, being built on the controllers path? It shouldn't have anything to do with it... right?
EDIT: After trying various suggestions, I've concluded there are three things to look at:
Each class has a namespace set, correctly describing the folder where the class is located
In the controller, have the statement "Use app\models\CarModel"
refer to the model in the controller.
Each seems to be correct, but I still get the error that it cannot find the model

This is a namespace problem in php.
You just use like this.
$car = new \App\Models\CarModel;
or
use App\Models\CarModel;
....
class {
$car = new CarModel;
}

First of all check name space in Model file , Define name space in model file
namespace App\Http\Models;
And then use
use App\Http\Models\CarModel;

Well, here it is. I solved it by asking myself this question: If I'm having so much trouble namespacing, referencing and organising my models, then maybe I can get artisan to do it for me.
The post that got me thinking differently was Mansoor Akhtar's advice here: How do I instruct artisan to save model to specific directory?
Get artisan to make the model in the right place first time.
php artisan make:model Models/CarModel
In the Controller, reference the model correctly
use name-of-app\Models\CarModel;
There may or may not be cache flushing involved in my problem. I was eventially restarting my XAMPP after every change to ensure no caching was involved. I also tried
php artisan cache:clear

You'll need to add a use statement to the top of your class.
Try:
use carfreak\Models\CarModel;
class ...
This assumes that your model is in the carfreak\Models namespace, and in a Models folder within your App / carfreak folder, otherwise you'll just need use carfreak\CarModel;.

I believe you have just ran the artisan command to create the model and you didn't move the CarModel file to Models folder. (Correct me if I'm wrong)
So in your controller add this before class declaration:
use carfreak\CarModel;
Then anywhere in your controller you can access the model like this:
$car = new CarModel;

Related

Customizable model file for a Laravel 5 package

I'm developing a Laravel 5 package where I have a "Member" model which currently extends App\User model. I would like to know the best practice to let any developer use a custom "Member" model instead of the one from the package. This is for example to allow a developer use another table.
One approach that seems to work without having done a deep test with it is to make an alias in my package service provider in the register() method:
$MemberModel = 'MyVendor\MyPackage\Member';
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('MyMember', $MemberModel);
In this case I have to:
Replace all entries in the code from the original class to the alias
Delete all php "use" entries related to it
Get the value of $MemberModel from a config file or the database
But I don't know if it is a good way to solve it or It may cause any conflict.
Is there any other and better approach for this goal? Thanks in advance!
I finally had to test by myself this approach without haven't read the solution anywhere else, but anyway everything seems to work fine in my source code.
If anyone is looking for doing anything similar, the code example in my question works because the $MemberModel is defined with a value. If you want to get that value from a Model instance, as me, you have to add that code in the boot() method of the service provider.

Loading a model inside a module from API in codeigniter

I have one module Foo in my codeigniter HMVC. Also I have an api controller inside my application/controllers. I want to load a model inside application/module/foo/models from application/controllers/testapi
I have tested it by autoload as
$autoload['model'] = array('foo/Foo_model');
and called from testapi
$this->load->model('Foo_model');
But its not working
Try
$this->load->model('foo/foo_model');
from your controller.
then call model's function like this
$this->foo_model->function_name();
save model in application/modules/foo/models/Foo_model.php
CodeIgniter loads all possible models from application/models, I would suggest you modify the path of your models to something like application/models/modules with this you can load your model using
$this->load->model('modules/foo/Foo_model')
If you do want to retain your folder structure, I suggest you look at the constant paths of CodeIgniter and start modifying them to your will (although this is not really recommended).

Laravel: conflict between model name and built-in facade

I have a Model in my Laravel app called Event. As I just discovered, this creates a conflict between my model and Illuminate\Support\Facades\Event, a built-in facade. The obvious solution here is to either change the name of my Model, which is not ideal because there is really no other name I could give my Model that makes any sense, or to rename the alias in app.php for Illuminate\Support\Facades\Event, which I'd like to avoid for fear of breaking anything that may rely on that alias in the future (I'm afraid I may forget).
It's been suggested that perhaps I could use namespaces, which I attempted as follows:
app/models/Event.php
namespace Models; #<-- I've also tried using "\Models" here
class Event extends \Eloquent{
app/database/seeds/DatabaseSeeder.php
Models\Event::create(); #<-- again, I've also used "\Models\Event"
All 4 combinations above have yielded a Class 'Models\Event' not found error when I run php artisan db:seed.
Perhaps I simply don't understand namespaces properly, but the more pressing issue is how to solve my problem. If it can be solved using namespaces as suggested, great, but I'm open to any other ideas as well.
I made this mistake early on as well, not necessarily understanding the role of namespace throughout the entire app.
The namespace should mark the business logic within the domain or responsibility of the app itself, so giving a namespace of Models isn't necessarily useful. Instead create a root namespace named after the app, your company, you, or whatever you like, then provide a Model sub-namespace.
For example:
namespace MyGreatApp\Models;
class Event extends \Eloquent{ }
Then you would reference this model under:
use MyGreatApp\Models\Event;
$event = new Event();
In the long run this is a cleaner and more organized approach. This does mean moving your models into a different folder, though. But there's nothing wrong with that. At least that way you know you have all your custom code in your MyGreatApp namespace. :)

Joomla how can i create model from other component

I'm a beginner in joomla. I create own component and would like to use model from other component (exactly contentbuilder).
I find few different ways how to create model but my problem is that
class ContentbuilderModelEdit extends JModel
use JPATH_COMPONENT_ADMINISTRATOR in it. When i create model ContentbuilderModelEdit i get warnings in lines that using JPATH_COMPONENT_ADMINISTRATOR constant.
Is it possible to create model using that constant from other component?
Thanks for your answers
Alas no. The JPATH_COMPONENT and JPATH_COMPONENT_ADMINISTRATOR are defined constants, and cannot be changed.
Sometimes the developers do this instinctively (it's easy) without realizing the kind of limitation they're putting on other developers. You might consider contacting the developers and propose such a change; if they accept, you won; if they don't, write a sed script that performs the changes (replacing it with JPATH_SITE and JPATH_ADMINISTRATOR . '/components/com_contentbuilder', and apply it after each update.
Or, copy their model into your component and rename it if it supports it.
:)
To call a model from another component you need firstly to include the path of this model:
JModelLegacy::addIncludePath(JPATH_SITE . '/components/comp1/models', 'Comp1Model');
Secondly you have to create an instance of your model:
$model = JModelLegacy::getInstance('Model1', 'Comp1Model');
After that you should be able to use the methods of your model.
ref link

CodeIgniter - where to put functions / classes?

Am having problems understanding where classes should be kept in CI. I am building an application that describes / markets mobile phones.
I would like for all of my functions (i.e. getphone, getdetails etc.) to reside in one class called Mobile - I understand that this file should be called Mobile.php and reside in the controllers folder.
Can I then have multiple functions inside Mobile.php? E.g.
public function getphone() {
xxx
xx
xx
}
public function getdetails() {
xxx
xx
xx
}
Or do I need to put each function in its own class?
I'd really appreciate looking at some sample code that works. I've been going through the documentation and google for a few hours, and tried all sorts of variations in the URL to find a test class, but without much luck! I've even messed around with the routes and .htaccess...
All I am trying to achieve is the following:
http:///model/HTC-Desire/ to be re-routed to a function that accepts HTC-Desire as a parameter (as I need it for a DB lookup). The default controller works fine, but can't get anything to work thereafter.
Any ideas?
Thanks
Actually it works like this:
Controllers and Models go to their perspective folders as you know it
If you want to create functions that are not methods of an object, you must create a helper file. More info here :
http://codeigniter.com/user_guide/general/helpers.html
Now if you want to create your own datatypes (classes that don't extend Models and Controllers), you add them to the library folder. So if let's say you want to create a class "Car" you create this file:
class Car{
function __construct(){}
}
and save it in the libraries folder as car.php
To create an instance of the Car class you must do the following:
$this->load->library('car');
$my_car = new Car();
More information on libraries here:
http://codeigniter.com/user_guide/general/creating_libraries.html
Yes, you can have as many functions in a controller class as you'd like. They are accessible via the url /class/function.
You can catch parameters in the class functions, though it's not advisable.
class Mobile extends CI_Controller{
public function getPhone($phoneModel=''){
echo $phoneModel;
//echo $this->input->post('phoneModel');
}
}
http://site.com/mobile/getPhone/HTC-Rad theoretically would echo out "HTC-Rad". HOWEVER, special characters are not welcome in URL's in CI by default, so in this example you may be met with a 'Disallowed URI characters" error instead. You'd be better off passing the phone model (or any other parameters) via $_POST to the controller.
Classes can exist both as Controllers and Models, as CodeIgniter implements the MVC pattern. I recommend reading more about that to understand how your classes/functions/etc. can best be organized.
Off the top of my head, Pyro CMS is an application built with CodeIgniter and the source code is freely available. I'm sure there are others.
I think it's best you handle it from one perspective, that is; create a utility class with all your functions in it.
The answer to the question of where to put/place the class file is the "libraries" folder.
This is clearly stated in the documentation. Place your class in the libraries folder.
When we use the term “Libraries” we are normally referring to the
classes that are located in the libraries directory and described in
the Class Reference of this user guide.
You can read more on creating and using libraries Creating Libraries — CodeIgniter 3.1.10 documentation
After placing the newly created class in the libraries folder, to use just simply load the library within your controller as shown below:
$this->load->library('yourphpclassname');
If you wish to receive several arguments within you constructor you have to modify it to receive an argument which would be an array and you loading/initialization would then be slightly different as shown below:
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('yourphpclassname', $params);
Then, to access any of the functions within the class simply do that as shown below:
$this->yourphpclassname->some_method();
I hope this answers your question if you have further question do leave a comment and I would do well to respond to them.

Resources