I'm exactly want to call function into function into class, like how exactly laravel works with oop php
example:
App\Flight::where('active', 1)->orderBy('name', 'desc') ->take(10)->get();
Is that impossible?
Your class methods need to return $this, which will allow you to chain calls like that.
you can call by using $this->functionName();
Related
I want to use the different queries inside one method and I want to pass a part of query inside that.
My method looks like this:
static function methodName($partOfQuery)
{
ModelName::where('...')->$partOfQuery->...;
}
And I want to do something like:
$partOfQuery = where('columnName', '>=', 5)->whereRaw('Other Condition');
self::methodName($partOfQuery);
But I was faced with this error:
Call to undefined function App\Classes\ClassName\where()
Anyone could help me with this issue? Thanks
I think that the error is because where is called without an eloquent model class.
Something you can do with query builder is to call a function inside your where condition like:
SomeModel::where(function($query){
// do something
$query->where(...)
})
I doubt there is nothing exactly like what you described. But there are alternatives, if I understand correctly, you are trying to chain multiple methods.
If so, you can do the following:
In your model class:
static function getActiveBooks()
{
return self::where('status', 'active');
}
public function getFeaturedBooks() {
return $this->getActiveBooks()->where('featured', 'active');
}
Usage:
$activeBooks = (new Book())->getFeaturedBooks()->get();
There are multiple ways, you can also use scope as #levi described in the comment section , they are 2 sides of the same coin.
I'm newbye of OOP and Laravel , but i have noticed that the operator with in laravel is used for a lot of things: for example i have found this part of code in the documentation:
return Redirect::to('register')->withErrors($validator);
withErrors? I know that with is used to pass multiple element to a view: is there more that i need to know about this operator?
Another Question: the validate class in php have this type of operator:
$validator->required('You must supply an email address.')->email('You must supply a valid email address')->validate('email', 'Email');
why i can use multiple "->" for a instance of the class validator? I know that in this way:
$object = new object();
$object->something(); //metod or attribute
but i know that it's impossible use the operator "-" for indicate multiple method/attribute for a class(even if it is a library).
thank you for all and i'm sorry for,maybe,the stupid question! Thank you!
Well Redirect::to() returns an instance of Illuminate\Http\RedirectResponse. This class has a method withErrors which is called in the example.
However this with* method is a bit different than the one to pass data to a view. withErrors flashes the data to the session so it is available for the next request (after the redirect happens)
Regarding your second question, this: $validator->required()->email() is called method chaining. It is used a lot (not only in Laravel) to achieve a nice and brief syntax.
What happens is that the methods return $this so you can call the next method on the same object right away.
Let's look at another example:
$result = User::where('active', true)->where('name', 'like', 'a%')->get();
If we now take a look at the where() method in Illuminate\Database\Eloquent\Builder you can see that after the where logic happens it returns $this so we can continue calling methods.
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
// code omitted for brevity
return $this;
}
Many Laravel classes implement this so-called Fluent Interface that allows method chaining for nearly every function call. Only methods that have an obvious return value can't be chained. Like retrieving a result with get(). Of course it has to return the result and it can't return $this as well.
You seem to understand the purpose of with() just fine.
As for your second question, you can "chain" object methods if the methods each return the object like this:
<?php
class MyClass {
public function myMethod()
{
// do stuff
return $this;
}
i am newer to cakephp. i am trying to write a function which not regarding to view(function). but when i call this function resultCall to undefined function. my code is below
public function records(){
$totalrec = $this->names->find('count');
$pages = ceil($totalrec/$limit);
return $pages;
}
and call it as
$rowsr = records();
please help
Where are you defining and using this function?
If you want to use it absolutely everywhere, define it in the bootstrap-file in config. But be aware that this heavily violates MVC.
Looking at the function, I would guess that you probably want to add this function to the names model. Than you can call it from the Controller this way: $this->Names->records() and in the model this way: $this->records().
actually i was searching for this.
$this->records();
this is working.
Thanks all friends.
Im trying to load my model in my controller and tried this:
return Post::getAll();
got the error Non-static method Post::getAll() should not be called statically, assuming $this from incompatible context
The function in the model looks like this:
public function getAll()
{
return $posts = $this->all()->take(2)->get();
}
What's the correct way to load the model in a controller and then return it's contents?
You defined your method as non-static and you are trying to invoke it as static. That said...
1.if you want to invoke a static method, you should use the :: and define your method as static.
// Defining a static method in a Foo class.
public static function getAll() { /* code */ }
// Invoking that static method
Foo::getAll();
2.otherwise, if you want to invoke an instance method you should instance your class, use ->.
// Defining a non-static method in a Foo class.
public function getAll() { /* code */ }
// Invoking that non-static method.
$foo = new Foo();
$foo->getAll();
Note: In Laravel, almost all Eloquent methods return an instance of your model, allowing you to chain methods as shown below:
$foos = Foo::all()->take(10)->get();
In that code we are statically calling the all method via Facade. After that, all other methods are being called as instance methods.
Why not try adding Scope? Scope is a very good feature of Eloquent.
class User extends Eloquent {
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
public function scopeWomen($query)
{
return $query->whereGender('W');
}
}
$users = User::popular()->women()->orderBy('created_at')->get();
Eloquent #scopes in Laravel Docs
TL;DR. You can get around this by expressing your queries as MyModel::query()->find(10); instead of MyModel::find(10);.
To the best of my knowledge, starting PhpStorm 2017.2 code inspection fails for methods such as MyModel::where(), MyModel::find(), etc (check this thread), and this could get quite annoying.
One (elegant) way to get around this is to explicitly call ::query() wherever it makes sense to. This will let you benefit from free auto-completion and a nice formatting/indentating for your queries.
Examples
BAD
Snippet where inspection complains about static method calls
// static call complaint
$myModel = MyModel::find(10);
// another poorly formatted query with code inspection complaints
$myFilteredModels = MyModel::where('is_foo', true)
->where('is_bar', false)
->get();
GOOD
Well formatted code with no complaints
// no complaint
$myModel = MyModel::query()->find(10);
// a nicely formatted and indented query with no complaints
$myFilteredModels = MyModel::query()
->where('is_foo', true)
->where('is_bar', false)
->get();
Just in case this helps someone, I was getting this error because I completely missed the stated fact that the scope prefix must not be used when calling a local scope. So if you defined a local scope in your model like this:
public function scopeRecentFirst($query)
{
return $query->orderBy('updated_at', 'desc');
}
You should call it like:
$CurrentUsers = \App\Models\Users::recentFirst()->get();
Note that the prefix scope is not present in the call.
Solution to the original question
You called a non-static method statically. To make a public function static in the model, would look like this:
public static function {
}
In General:
Post::get()
In this particular instance:
Post::take(2)->get()
One thing to be careful of, when defining relationships and scope, that I had an issue with that caused a 'non-static method should not be called statically' error is when they are named the same, for example:
public function category(){
return $this->belongsTo('App\Category');
}
public function scopeCategory(){
return $query->where('category', 1);
}
When I do the following, I get the non-static error:
Event::category()->get();
The issue, is that Laravel is using my relationship method called category, rather than my category scope (scopeCategory). This can be resolved by renaming the scope or the relationship. I chose to rename the relationship:
public function cat(){
return $this->belongsTo('App\Category', 'category_id');
}
Please observe that I defined the foreign key (category_id) because otherwise Laravel would have looked for cat_id instead, and it wouldn't have found it, as I had defined it as category_id in the database.
You can give like this
public static function getAll()
{
return $posts = $this->all()->take(2)->get();
}
And when you call statically inside your controller function also..
I've literally just arrived at the answer in my case.
I'm creating a system that has implemented a create method, so I was getting this actual error because I was accessing the overridden version not the one from Eloquent.
Hope that help?
Check if you do not have declared the method getAll() in the model. That causes the controller to think that you are calling a non-static method.
For use the syntax like return Post::getAll(); you should have a magic function __callStatic in your class where handle all static calls:
public static function __callStatic($method, $parameters)
{
return (new static)->$method(...$parameters);
}
Is there a way to instantiate a class and call one of its methods in one line? I hoped the following would work but it doesn't:
(new User())->get_name();
I know this question is old but the replies can be misleading.
Since version 5.4 you can instantiate and call methods inline:
(new Foo())->bar();
http://docs.php.net/manual/en/migration54.new-features.php
This is not possible. You could, however, create a static method returning a new instance. Something like:
class User {
public static function create() {
return new self();
}
}
User::create()->get_name();
Nope, sorry, this unfortunately doesn't work in PHP. You could work around it by using a static factory method or something like that though.
Try if this works for you. It calls the function from the class not an object.
User::get_name();