How to use User Defined Functions in Laravel - php

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]);
}

Related

Laravel - Automatically load Auth::user() relations

I was wondering if it's possible somehow to automatically load all Auth::user() relationships.
Auth::user() returns an instance of my App\Models\Auth\Usuario.php, and inside Usuario.php class I have some relationships with another models.
The way I'm doing it now manually loads the relations with $user->load('relation') but I need to do it in every request.
I was thinking to do something like this in my base Controller:
public function __construct()
{
$user = Auth::user();
$this->relation = $user->load('relation');
}
But It's not exactly what I'm looking for.
There is another/best way to load all the Auth::user() class relationships? Like middleware or something?
You can use the $with property on your model to declare relationships that should always be eager loaded.
From the docs:
Sometimes you might want to always load some relationships when
retrieving a model. To accomplish this, you may define a $with
property on the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
/**
* The relationships that should always be loaded.
*
* #var array
*/
protected $with = ['author'];
/**
* Get the author that wrote the book.
*/
public function author()
{
return $this->belongsTo('App\Author');
}
}
I'm using a view shared variable set in a middleware, so here is a example
the route:
Route::prefix('accounts')->middleware(['auth', 'profile'])
the middleware (profile) :
view()->share('currentUser', Auth::user()>setRelations(['profile']));
in any view:
$currentUser->profile->description
I am not sure why you are manually loading relations, this should be done within your model?
Anyway to answer your question, i use a helpers.php which I add to composer autoload:-
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"app/helpers.php"
]
within this helpers file you could decalare custom global methods:-
function current_user()
{
return auth()->user();
}

PHP Slim 3 Framework - where can I put my controller file?

I registering a controller with the container, but it seems not working because it doesn't match to the correct location.
\slim\src\routes.php
<?php
// Routes
$app->get('/dd', 'App\controllers\HomeController:home');
\slim\App\controllers\HomeController.php
<?php
class HomeController
{
protected $container;
// constructor receives container instance
public function __construct(ContainerInterface $container) {
$this->container = $container;
}
public function home($request, $response, $args) {
// your code
// to access items in the container... $this->container->get('');
return $response;
}
public function contact($request, $response, $args) {
// your code
// to access items in the container... $this->container->get('');
return $response;
}
}
My project folder structure:
\slim
  \public
    index.php
    .htaccess
  \App
    \controllers
      HomeController.php
  \src
    dependencies.php
    middleware.php
    routes.php
    settings.php
  \templates
    index.phtml
  \vendor
    \slim
Maybe I should to setting \slim\src\settings.php?
Because it show Slim Application Error:
Type: RuntimeException Message: Callable
App\controllers\HomeController does not exist File:
D:\htdocs\slim\vendor\slim\slim\Slim\CallableResolver.php Line: 90
Last, I also refer to these articles:
https://www.slimframework.com/docs/objects/router.html#container-resolution
PHP Slim Framework Create Controller
PHP Slim Framework Create Controller
How can i create middleware on Slim Framework 3?
How can i create middleware on Slim Framework 3?
Add psr-4 to your composer file so that you're able to call your namespaces.
{
"require": {
"slim/slim": "^3.12
},
"autoload": {
"psr-4": {
"App\\": "app"
}
}
}
This PSR describes a specification for autoloading classes from file paths. Then in your routes.php file add this at the top :
<?php
use app\controllers\HomeController;
// Routes
$app->get('/dd', 'App\controllers\HomeController:home');
and finally in your HomeController.php file add :
<?php
namespace app\controllers;
class HomeController
{
//.. your code
}
hope this helps...:)

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 call view from an other file than controller

I am creating a laravel 5.2 package, following are my files:
packages/
-Shreeji/
--Ring/
---composer.json
---src/
----Ring.php
----RingModel.php
----RingServiceProvider
----Views/
-----ringslist.blade.php
composer.json
{
"name": "shreeji/ring",
"description": "Simple",
"license": "MIT",
"authors": [
{
"name": "author",
"email": "email#gmail.com"
}
],
"autoload": {
"psr-4": {
"Shreeji\\Ring\\": "src/"
}
},
"minimum-stability": "dev",
"require": {
"Illuminate/support": "~5"
}
}
Ring.php
namespace Shreeji\Ring;
use Illuminate\Http\Response;
Class Ring {
function __construct() {
}
public function get_all()
{
return view("ring::ringlist");
}
}
RingServiceProvider.php
namespace Shreeji\Ring;
use Illuminate\Support\ServiceProvider;
Class RingServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('ring', function($app){
return new Ring;
});
}
public function boot()
{
$this->loadViewsFrom(__DIR__ . '/Views', 'ring');
}
}
ringlist.blade.php
<!DOCTYPE html>
<html>
<body>
<h1>Welcome</h1>
</body>
</html>
And in app/Http/Controllers I have created a test file like this:
Ringcontroller.php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Shreeji\Ring\Ring;
class RingController extends Controller
{
public function index()
{
$ring = New Ring();
$ring->get_all();
}
}
When I call the controller, browser keeps loading and crashed systematically. I don't know if I can use view outside any controller class like such.
Let me know if I did any mistake in calling view from Ring.php file.
Couple issues I see:
You want to use views, but your package does not require the illuminate/view package. You need to update your composer.json file to require "illuminate/view": "~5".
The view() function is a helper method included at Illuminate\Foundation\helpers.php. Unless you want to depend on the entire Laravel framework just for this function, you will need to create your own view() function. The code is below, where you put it is up to you.
if (! function_exists('view')) {
/**
* Get the evaluated view contents for the given view.
*
* #param string $view
* #param array $data
* #param array $mergeData
* #return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
*/
function view($view = null, $data = [], $mergeData = [])
{
$factory = app(ViewFactory::class);
if (func_num_args() === 0) {
return $factory;
}
return $factory->make($view, $data, $mergeData);
}
}
Once you get the view stuff working, you can make views all day long, but if you don't return anything from your controller, you're not going to see anything. Make sure you return something from your controller methods.
You can use somethin like view composer Docs
In your RingServiceProvider register a composer
use Illuminate\Contracts\View\Factory as ViewFactory;
public function boot(ViewFactory $view)
{
$view->composer('*', 'App\Http\ViewComposers\SomeComposer');
}
And in App\Http\ViewComposers\SomeComposer
use Illuminate\Contracts\View\View;
public function compose(View $view)
{
$view->with('count', '1');
}
Play around with it, basically I am using it share $variables on particular views but maybe this can help you achieve what you want.
Or u can just use Illuminate\Contracts\View\View; to load your view that you need!

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() }}

Categories