I have a problem with code using Laravel. I define an attribute in a model to get a list. It takes a lot of time. I use this model in a controller. Follow the code:
protected $appends=["consume_info"];
public function getConsumeInfoAttribute(){
//query a lot of information from mysql
}
I'm wondering if there is an attribute in Controller or Model to avoid a query with mysql in model.
Is there a setting to tell Laravel when to load this appended attribute or not?
Why not just remove the consume_info from $appends array. You will get the $model->consumer_info and that too only when you need this.
Related
I have override boot function inside the laravel model, code structure something like this:
class modelName extends Model
{
protected static function boot(){
parent::boot();
self::creating(function ($model){
//Do Some Stuff
});
}
This is working fine when I'm calling create a function, like this:
modelName::create($tmpArray);
But it's not working when I want to use insert function:
modelName::insert($tmpArray);
Now I want to call boot function when insert function called, I've two-dimensional array; in that case, I've only insert function to save data in a single row.
Events are only called when using the Eloquent functions to save/update/delete records.
If you want events to be triggered when saving multiple records, you could try to use Model::createMany($arrayOfObjects). However, checking the source code for this function, it will actually run a separate query for each record that's in the array. So if you got a whole lot, you might need to think of a different route.
creating is event of eloquent model.
insert() is not method of eloquent model, its method of db queries.
try to use eloquent method instead of db query.
see laravel doc for eloquent methods
see Db queries method
for two two-dimensional array can use eloquent method of createMany or saveMany
difference between save and create is that save accepts a full Eloquent model instance while create accepts a plain PHP array.
you can refer laravel docs Inserting & Updating Related Models
I'm implementing a small project to maintain a list of books. I'm using PHP 7, Laravel 5.5, Eloquent and SQLite.
I created a Model class book and the respective resource controller BookController. For the sake of simplicity, a book only has to public properties: title and author.
Furthermore, I created an AdminController that creates an admin page. I want to use this page to add books to the database and remove other ones.
My BookController has a store() function:
public function store(Request $request)
{
// Validate the request...
$book = new Book;
$book->title = $request->title;
$book->author = $request->author;
$book->save();
}
My AdminController has a HTML form with input fields for new books (one for title, one for author) as well as a submit button. This button calls AdminController#post.
Now I wonder how to actually add the book from there.
Should I call the BookController from the AdminController and pass the request object to the BookController? Is this the way, controllers communicate in Laravel? Or should I avoid the store function and add the functionality to the AdminController directly?
I think you should separate two controller for two purposes. You can declare variable as Book model in other controllers and work with it.
You can using BookController for both, just need to define two routes for one controller and write some logic in the store method, my viewpoint... that is not good way. Because it need check some vars to detect which request from admin and from user. I don't want to make some thing complex between workflow of user & admin.
I am trying to use custom method in User model with class name User in laravel4.1. i changed the $table attribute to my table name and added a custom method names 'public function abc' in user model. Then in my user controller i tried like this :-
$u= new User;
$u->abc();
but its not working and giving following error :-
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::abc()
and i dnt know why this happening everything seems fine,help me out in this guys.
UPDATE :SOLVED ,Done Nothing
I DO NOT KNOW WHAT IS THE PROBLEM WITH LARAVEL
$u= new user;
$u->abc();
i just changed User to user and its started working and i dnt even know why ,anyone know reason??
Every method on a Model get passed on to a new QueryBuilder
User::where()
User::find()
User::{relationship}()
If you instantiate a model like this
$user = User::find()->method();
it will work. Don't try to make your Eloquent models too fat.
Just create a Repository to make your Controllers as thin as possible and your Eloquent just as intelligent as it can be by using the tools given by Eloquent (relationships, hidden attributes, accessors & mutators, $this->appends, ...)
Everything else belongs in your Repositories.
Try running
composer dumpautoload
If this doesn't work, be sure that there is only one class called User in your whole project. There may be a package, migration or something with the same name. Try putting your custom User class in a namespace.
I am looking for a way how to attach a behavior to model displayed in a grid view in Yii Framework. The grid view is using CActiveDataProvider and I need every $data element to have a behavior attached to it. The model shouldn't attach the behavior after construct, since it is related to the grid view only.
Thanks
You can create the following class to use to create a data provider.
ActiveDataProvider extends CActiveDataProvider{
public function getData(){
$data = parent::getData();
foreach($data as &$model){
$model->attachBehavior('aName', new mybehavior());
}
return $data;
}
}
Another option (instead of creating a CActiveDataProvider override as suggested in another answer) is to do all your model querying ahead of time and attach your behaviors in your controller. Then pass to a CArrayDataProvider.
Hmm, thinking about it, I like the other approach better :-) I'll leave this for completeness sake.
I have a controller/model for projects. so this controls the projects model, etc, etc. I have a homepage which is being controlled by the pages_controller. I want to show a list of projects on the homepage. Is it as easy as doing:
function index() {
$this->set('projects', $this->Project->find('all'));
}
I'm guessing not as I'm getting:
Undefined property: PagesController::$Project
Can someone steer me in the right direction please,
Jonesy
You must load every model in the controller class by variable $uses, for example:
var $uses = array('Project');
or in action use method
$this->loadModel('Project');
In my opinion the proper way to do this is add a function to your current model which instantiates the other model and returns the needed data.
Here's an example which returns data from the Project model in a model called Example and calls the data in the Example controller:
Using Project Model inside Example Model:
<?php
/* Example Model */
App::uses('Project', 'Model');
class Example extends AppModel {
public function allProjects() {
$projectModel = new Project();
$projects = $projectModel->find('all');
return $projects;
}
}
Returning that data in Example Controller
// once inside your correct view function just do:
$projects = $this->Example->allProjects();
$this->set('projects', $projects);
In the Example view
<?php
// Now assuming you're in the .ctp template associated with
// your view function which used: $projects = $this->Example->allProjects();
// you should be able to access the var: $projects
// For example:
print_r($projects['Project']);
Why is this "better" practice than loading both models into your controller? Well, the Project model is inherited by the Example model, so Project data now becomes part of the Example model scope. (What this means on the database side of things is the 2 tables are joined using SQL JOIN clauses).
Or as the manual says:
One of the most powerful features of CakePHP is the ability to link relational mapping provided by the model. In CakePHP, the links between models are handled through associations.
Defining relations between different objects in your application should be a natural process. For example: in a recipe database, a recipe may have many reviews, reviews have a single author, and authors may have many recipes. Defining the way these relations work allows you to access your data in an intuitive and powerful way. (source)
For me it's more reasonable to use requestAction. This way the logic is wrapped in the controller.
In example:
//in your controller Projects:
class ProjectsController extends AppController {
function dashboard(){
$this->set('projects', $this->Project->find('all'));
}
$this->render('dashboard');
}
Bear in mind that you need to create dashboard.ctp in /app/views/projects of course.
In the Page's dashboard view (probably /app/views/pages/dashboard.ctp) add:
echo $this->requestAction(array('controller'=>'projects', 'action'=>'dashboard'));
This way the logic will remain in the project's controller. Of course you can request /projects/index, but the handling of the pagination will be more complicated.
more about requestAction(). but bear in mind that you need to use it carefully. It could slow down your application.