Custom class in laravel - php

I've created a custom class inside the app/Helpers folder.
I want to access it in views like Helper::someMethod(). I tried to bind it in IoC. But couldn't get it working. The following is my Helper class:
class ApplicationHelpers {
public function me() {
return "this is me!";
}
}
This is how I bind it in the AppServiceProvider class in register method.
$this->app->make('App\Helpers\ApplicationHelpers');
And this is how I want to access in view.
<div class="title m-b-md">
{{ ApplicationHelpers::me() }}
</div>
How can I achieve this?

Inside config/app.php aliases array add this line
'Helper' => App\Helpers\Helper::class, //your class path
then use composer dump-autoload
Then you can use helper function in view like this
{{Helper::userInfo()}} or {{Helper->userInfo()}}
Helper is alias name and function. use :: or -> based on function definition.

If you do not register the class anywhere, you have to include the namespace. So it would look like this:
<div class="title m-b-md">
{{ \App\Helpers\ApplicationHelpers::me() }}
</div>
Or you can create an alias in your config/app.php and then call the class directly.

if you want to add simple functions helpers you can also edit your composer.json file and add the path to your helper file
"autoload": {
"files": [
"app/Http/ApplicationHelpers.php"
],
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
where you can declare simple function such as me()
function me() {
return "this is me!";
}
then call composer dump-autoload
so you can simply call
<div class="title m-b-md">
{{ me() }}
</div>

Related

How to Use Function inside #foreach - Laravel

Thanks For Reading.
I'm new in Laravel, i want to try to change the output of Database with #foreach blade, there is the example :
This is Route :
Route::get('/home', 'warnajati#index');
This is Controller :
public function index()
{
$post = DB::table('posts')->get();
return view('warnajati', ['posts'=>$post]);
}
This is Views :
#foreach ($posts as $post)
<div class="title"><h3>{{$post->title}}</h3></div>
#endforeach
with Output of $post->title is "This is The Looonger Title you ever know" ,
and i want to make the title is shorter with Wordlimit() function i have made :
function wordlimit($text, $limit=10)
{
if (strlen($text)>$limit) {
# code...
$word = mb_substr($text,0,$limit-3)."...";
}else{
$word =$text;
}
};
How and Where i must place that function in laravel Project ?? please help me..
Your function has no return value... Laravel already has this function: http://laravel.com/docs/5.3/helpers#method-str-limit
#foreach ($posts as $post)
<div class="title"><h3>{{ str_limit($post->title, 10) }}</h3></div>
#endforeach
You can use Laravel's Accessor for doing that like this inside a Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function getShortTitleAttribute($value)
{
// return shortened title here ...
}
}
and then you can use it in blade like this:
{{ $post->short_title }}
Hope this helps!
You can put your function in helpers.php file from libraries folder.
Just make sure that you have helpers.php file autoloaded in composer.json file:
"autoload": {
"files": [
"libraries/helpers.php"
],
},
If you had to add this to your composer.json you will also have to run composer dump-autoload command from terminal.
For more info check out Best practices for custom helpers on Laravel 5.

calling function from controller in view laravel

this is a simple thing actually but since im new in laravel it trouble me, i have this function
class HomeController extends Controller {
public $layout = 'layouts.master';
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('landing-page')
->with('title','Landing Page')
->with('users',User::member()->get());
}
<!-- HOW TO CALL getDate Function in my view -->
public function getDate(){
$mytime = Carbon::now()->format('f');
$response = array
(
'content' =>$mytime,
'status' =>'success',
);
return Response::json($response)->view('landing-page');
}
}
how to call it in my laravel view? i search all over the internet but i not quite understand since programming is new for me i already tried something like this in my view using routes {{url('date')}}, {{$mytime}}, but none working, well i can call a function if there's certain event happen like clicking button or else but if no certain event it's quite confusing me
<p>Month :{{url('date')}}</p>
<p>Month :{{$mytime()}}</P>
above are some ways i tried to call the function
UPDATE WHAT I'VE TRIED BASED on #tptcat answer and work
create helpers.phplocated under files `app\helpers.php
<?php
use Carbon\Carbon;
if (! function_exists('myGetDate')) {
function myGetDate()
{
$mytime = Carbon::now()->format('F');
return $mytime
}
}
composer.json
"autoload": {
"files":[
"App/helpers.php"
],
calling function in my view
{{myGetDate()}}
This isn't a hard and fast rule, but part of using a framework is to somewhat buy into its conventions and use them to your advantages.
Generally speaking, your Controllers are for working with HTTP (GET, POST, PUT, etc.). They're not designed to be indiscriminate ways to call methods from your Views.
I would recommend doing something like this instead:
// app/Utilities.php
<?php
class Utilities
{
public static function getDate()
{
// your code
}
}
then in your view:
{{ Utilities::getDate() }}
or:
// app/helpers.php
<?php
if (! function_exists('myGetDate')) {
function myGetDate()
{
// your code
}
}
then in your view:
{{ myGetDate() }}
and then in composer.json autoload whichever file you create:
"autoload": {
"files": [
"app/Utilities.php"
]
}
or...
"autoload": {
"files": [
"app/helpers.php"
]
}
and then run composer dump-autoload.
Another way to approach this could be using Blade Service Injection (introduced in Laravel 5.1). This technically can be done with your controller:
// In your blade template
#inject('service', 'App\Http\Controllers\HomeController')
{{ $service->getDate() }}
But I'd still recommend not having a method in your controller in charge of returning this data if it's going to be called as a method from a Blade template. Using some type of service class would be more appropriate:
// app/Utilities.php
<?php
namespace App;
class Utilities
{
public function getDate()
{
// your code
}
}
// In your blade template
#inject('service', 'App\Utilities')
{{ $service->getDate() }}
and in this case you wouldn't need to add it to the files autoload array in composer.json.
For what it's worth, not knowing anything else about your project, I would choose one of the first two options, and more likely the helpers.php option.
Try this:
class HomeController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$title = 'Landing Page';
$users = \User::member() - > get();
$mytime = \Carbon::now()->format('f');
return view('layouts.master.landing-page', [
'title' => $title,
'users' => $users,
'mytime' => $mytime
]
);
}
}
And to display it within the landing-page view you would access them with:
{{ $title }}
{{ $users }}
{{ $mytime }}

How to use User Defined Functions in Laravel

I am new to Laravel. I want use some Own Functions. Where do Write the Function.
<?php function userrole1($roleid) {
$userrole=DB::table('roles')->where('id', '=', $roleid)->get();
?>
#foreach($userrole as $val)
<?php echo $val->role_title; ?>
#endforeach
<?php
}
?>
New Way to add Helpers
1: I created folder app/Helpers
2: In app/Providers I created new provider file HelperServiceProvider.php
3: In this file I registered all helpers classes I need
$this->app->bind('dateHelper', function()
{
return new \App\Helpers\DateHelper;
});
In config/app.php I added this new provider
'App\Providers\HelperServiceProvider',
Use This helper function dateHelper
Old Way
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 this run composer dump-autoload command in cmd
You need to create and register your own helpers file:
http://laravel-recipes.com/recipes/50/creating-a-helpers-file
After that you'll be able to use custom helpers (functions) in your app.
Just make a function in the model class and include model and call it from the controller as pass from there to the view using variable. thats it.
In Model User(you can make any):
public function userrole1($roleid) {
$userrole=DB::table('roles')->where('id', '=', $roleid)->get();
return $userrole
}
In Controller:
use App\User
public function __construct(User $user){
$this->user_model = $user;
}
public function index(){
$userRole = $this->user_model->userrole1()
return view('admin/index', ['userRole' => $userRole]);
}

Helpers in Laravel5

I have a problem with helpers , I create correctly the helper and I can call this helper that I created in view but when I need to access to property.
{{Text::showBanner()}};
The function of helperI created called showBanner
public static function showBanner() {
$banner= Banner::all();
return $banner;
}
How can I access to attribute id of $banner ?
UPDATED
When I use this
#foreach ( $banners as $item)
{{$item}}
#endforeach
I need to change this $banner for this helper
create a file app/helpers.php with your desired code:
function showBanner() {
$banner = Banner::all();
return $banner;
}
Autoload it with composer
{
"autoload": {
"files": [
"app/helpers.php"
]
}
}
use it {{ showBanner() }}

Laravel 5 steam condenser

Composer.json
"autoload": {
"classmap": [
"database"
],
"files": [
"vendor/koraktor/steam-condenser/lib/steam-condenser.php"
],
"psr-4": {
"App\\": "app/"
}
},
HomeController
public function index()
{
$server = new SourceServer('80.67.11.46:27025');
try {
$server->rconAuth('abc123');
echo $server->rconExec('status');
}
catch(RCONNoAuthException $e) {
trigger_error('Could not authenticate with the game server.',
E_USER_ERROR);
}
}
I have updated the composer after adding, dump-autoload and tried all the solutions i can find with namespaces and so on.
But can't still use the steam condenser classes, any solution for this ?
The error Class 'App\Http\Controllers\SourceServer' not found denotes the fact that you're inside the App\Http\Controllers namespace and as such it will try to find the SourceServer class within that namespace. Prepend \ to your class name to call it in a global context:
$server = new \SourceServer('80.67.11.46:27025');
Or add this after the namespace declaration at the top of your controller:
use SourceServer;
And remove the class mapping from composer.json because it's not needed. You can read up more on how namespaces work in the PHP Namespaces Documentation.

Categories