laravel 8 Dynamically create Class object based on string - laravel

Hi i am trying to show all count for left sidebar menu but unfortunately i am getting error class not found Class 'app/Http/Helpers/Helpers.php' not found please help me how can id do that thanks.
app/Http/Helpers/Helpers.php
function NotificationCount()
{
return Example::where('status', 1)->where( 'created_at', '>', Carbon::now()->subDays(3))->latest()->count();
}
leftsidebar
#php
$className = 'app/Http/Helpers/Helpers.php';
$count = new $className();
return $count->NotificationCount();
#endphp

Best Practices for custom helpers in Laravel.
Create a helpers.php file in your app folder and load it up with composer:
"autoload": {
"classmap": [
...
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php" // <---- ADD THIS
]
},
After adding that to your composer.json file, run the following command:
composer dump-autoload
add your function
function propertyNotificationCount()
{
return Property::where('status', 1)->where( 'created_at', '>', Carbon::now()->subDays(3))->latest()->count();
}
in helper.php file
Now in any blade file you can call propertyNotificationCount() this function.

As far as I know, it's not really a good practice to use #php #endphp inside blade templates.
I would probably consider another approach and try to return the notification count from the controller somehow and inside php you could handle more easily the class not found error ( maybe just declare it with use at the begging of the controller and you can use it afterwards )

Related

How to fetch data from table in model in larvel framework and directly use in view?

I have created a model like below
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class countData extends Model
{
//
public function countAbc () {
// i don't know how to write in laravel query so for understanding purpose i wrote in simple pg query
$sql=pg_query("select count(*) as countrow from s_abc");
$countfetch=pg_fetch_array($sql);
return $countfetch[0];
}
}
I don't have any route for this function. On view page I am check
#if( $Item->ClassID == 'abc' )
{
//then call the above model and use countAbc () function
countAbc();
}
Basically my view is already loaded, I need to check the condition and call the above model to count the data.
I think you're looking for helper function.
In question you've created countAbc() function and you want to call it everywhere.
Use to make function in helpers.php file instead of model file
Create a helpers.php file in your app folder and load it up with composer:
"autoload": {
"classmap": [
...
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php" // <---- ADD THIS
]
},
After adding that to your composer.json file, run the following command:
composer dump-autoload
Afterward, put your this function in helpers.php
public function countAbc () {
$sql=pg_query("select count(*) as countrow from s_abc");
$countfetch=pg_fetch_array($sql);
return $countfetch[0];
}
Now, You can access it anywhere.
public function countAbc () {
$counts_abc = \DB::table('s_abc')->count();
return $counts_abc;
}
Create a model that corresponds to the table:
php artisan make:model Sabc
Open that model file, and set the table name:
protected $table = 's_abc';
If you want to get the count of the amount of rows within your table that corresponds to the model, it's simple:
Sabc::count();
First Of All I think you have to look Laravel Framework structure: Laravel Directory Structure And contents inside it.
Basically you don't have to define route to fetch data from database.
You have to define model properly - long story short every table in your database have to have one model in your app.
You have tablse s_abc You have to define model SAbc.
php artisan make:model SAbc - this command will make model for you.
After that you can use Eloquent aggregate functions to get count or you can write your own method in it:
Using Aggregate function:
...
use App\SAbc;
...
class SomeClass {
...
$count_sabc = SAbc::count();
...
}
...
Using Your Own Method
In your model write:
...
class SAbc extends Model {
public function getCount() {
return self::count();
// Or with raw query
// return self::selectRaw('count(*) as count')->first()->count
}
}
...
// Then you can use this methd anywhere you want like that:
(new SAbc)->getCount();
Hope this helps you

Laravel 5.4 - Access Static Method inside Controller Method

in my Laravel controller, I am trying to access a static method on a 3rd party library from a method inside the controller, but I always get the error:
"Fatal error: Class 'App\Http\Controllers\geoPHP' not found".
While on a breakpoint using VS Code, I can use the terminal and access the static method. Thoughts?
In the controller, I have the method to just get the version of the static class software:
public function parseKMLFile() {
$test = geoPHP::version();
}
In composer, in the autoload section, I have:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Library/geoPHP/geoPHP.inc",
"app/Library/gpointconverter.class.php",
"app/Library/gpoint.php"
]
},
Thanks in advance
You have to be careful with namespace convention, in the controller you are in the App\Http\Controllers\ namespace, so if you want to call your custom class you have to explicit escape the controller namespace, i.e:
$test = \geoPHP::version();

How to autoload service namespace in laravel 5.6

I have created some library services in app\Library. I used AppServiceProvider to bind that service using following code:
$this->app->bind('App\Library\Globalfunction', function ($app) {
return new Globalfunction();
});
app\Library\Globalfunction.php
<?php
namespace App\Library;
class Globalfunction {
protected $_ci;
public $siteConfig=array();
public $smtpConfig=array();
public $socialConfig=array();
public $paramConfig;
public $paramFrom;
public function test($param) {
return $param;
}
}
?>
To use this test() in controller i am including namespace using following:
use App\Library\Globalfunction;
once namespace is included i use following code:
$globalFunction = new Globalfunction();
echo $globalFunction->test('hello');
All of this code working fine but i don't want to add use App\Library\Globalfunction; in each file so is there anyway i can do that? is there any autoload file where i can put this and i can access Globalfunction?
I google solution for that and i tried several solutions like add this in composer or create package etc but it's not working so please if anyone have solution for this problem please let me know.
Maybe you can follow the same approach as Laravel?
Let me give you an example on how to achieve this.
First, create a Helpers.php file in app/Helpers.php.
You also need to autoload it.
"autoload": {
"classmap": [
"database/seeds",
"database/factories",
"database/providers"
],
"files": [
"app/Helpers.php"
],
"psr-4": {
"App\\": "app/"
}
}
Once that is done, you could define a function as such in your newly autoloaded Helpers.php:
if(! function_exists('global_function')) {
function global_function()
{
return new \App\Library\Globalfunction();
}
}
Then to use it anywhere, you can just do this.
global_function()->test('hello');
This is just a simple example. Obviously there are a lot of considerations you have to make before implementing this.
However, Laravel has a similar approach to providing global helper functions. For example:
use Illuminate\Support\Facades\Session;
// This
echo Session::get('key');
// is the same as
echo session()->get('key');

Where are namespaces declared in Laravel?

I learned in php that to be able to use a namespace, you have to declare or include first.
<?php
namespace namespace_01;
function f1()
{
echo 'this is function';
}
use namespace_01 as test_namespace;
test_namespace\f1();
?>
Almost all of laravel codes use namespaces. But where are they defined?
Example,
when I created a controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class controller1 extends Controller
{
//
}
where is Illuminate\Http\Request defined?
Open file from vendor/laravel/framework/src/Illuminate/Http/Request.php
There you will see the namespace declared on top as namespace Illuminate\Http; and the class name is Request
and you can see in your composer.json file
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
so all the classes inside App folder are auto loaded with composer and also the vendor files. you don't need to include files every time.
These are found in the Laravel Framework. Laravel uses composer to automatically load these packages. You can find the source in your /vendor folder, this is where composer puts the packages.

Laravel global function

I have 2 models:
Bill:
id, account_id, descripcion, monto_pagado, saldo
Payment:
id, bill_id, monto
Each time someone insert a new bill to the account or insert a new payment I pretend to calculate the balance of the account.
What would be the best place to accomplish this:
as service
as mutators in the model
as function in the controller
I know i would have to call this in others places of my project. So i would like it to be a global function. What would be the best place to do it?
You could use an event in your models. Use creating if you want to calculate before the model is actually created in the database, or created if you want to calculate after it has been created.
In your App\Providers\AppServiceProvider::boot() method, define the events for both models:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Bill::creating(function ($bill) {
// Do something with $bill
});
}
// etc
}
To avoid code repetition, you may use a trait and use it in both classes. Call it PretendCalculationTrait for example and place it in app/Traits (create the directory if needed):
<?php
namespace App\Traits;
trait PretendCalculationTrait
{
public function pretendCalculate()
{
// Do your stuff
}
}
Then in your model, use this trait:
class Bill extends Eloquent
{
use App\Traits\PretendCalculationTrait;
// etc.
}
Finally, in your AppServiceProvider, call the method defined in the trait:
public function boot()
{
Bill::creating(function ($bill) {
return $bill->pretendCalculate();
});
Payment::creating(function ($payment) {
return $payment->pretendCalculate();
});
}
See Laravel Model Events documentation for more details.
One possible solution, since you mentioned wanting it to be a global function, is to use Laravel's autoloading feature.
Create a file that contains the function for your calculation. It can be placed anywhere, and contain other functions, but for brevity we'll place it here: App/Http/customFunctions.php. In your file, create your function:
function pretendCalculation()
{
return $something;
}
Next, tell Laravel to autoload it by adding it to your autoloading list in composer.json:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Http/customFunctions.php" <-- Here is the new file
]
Then just execute a composer dump auto-load -o or the like, and now you'll have access to this file/all functions within the file, anywhere in your application.

Resources