How to Use Function inside #foreach - Laravel - php

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.

Related

laravel variable in view with parameters

I would like to send a parameter from view to controller.
How to do this in the views blade and controllers ?
DB::table('news')->where('id', '=', 1)->get()
So everything works. But I would like it to look nicer. e.g
{{ $news->id='1' }}
This is my beginnings with laravel.
I'ld suggest you try sending data to controller via route as mentioned in other answers. But if you still don't want route, try this method.
Make your controller function as static. Eg:
public static function newsFunc($id){ //** static
$data = DB::table('news')->where('id','=', $id)->get();
.
.
.
.
.
}
In your view call
{{ \App\Http\Controllers\YourControllerName::newsFunc($news->id) }}
It doesnt look like a good idea to send any data FROM view TO controllers
But if you really need it, you can pass controller object to view and interact with it in blade file:
class CatalogController extends Controller
{
public function showNews()
{
return view('catalog.sections', [
'controller' => $this,
]);
}
}
your blade file:
<div>
#php($controller->doSomething())
</div>
In your Blade template you can call a route like:
<a href="{{route('something',$news->id)}}"
And in your route file you declare this route:
Route::get('something/{id}','yourController#yourMethod');
In your controller you can retrieve it:
public function yourMethod($id){
//here u can use $id
}
So this is something that you could do with another route.
So you can register your route like this:
Route::get('/news/{id}', 'YourController#getNews');
And then your controller would have a method:
public function getNews($id) {
$news = DB::table('news')->where('id', '=', 1)->first();
return view('your-view', compact('news'));
}
And in your view to pass the id you would have something like:
Go to first
Hope that 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 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() }}

Global queries in laravel 5

Controller:
$categories = Categories::get();
return view('coolpage', ['categories' => $categories]);
Blade View:
<ul>
#foreach ($categories as $category)
<li>{{ $category->title }}</li>
#endforeach
</ul>
This works perfect on individual views.
I want to be able to have these categories show up on every page (this will be used as a dropdown menu in the header navbar). I have app.blade.php that contains the header html and #yield('content'). The only way I can think of querying out the categories is somehow putting it in my routes files... which I'm pretty sure is not the way to go.
I'm hoping to get suggestions / examples.
As described in the Laravel documentation, you can use a wildcard view composer to accomplish this.
First you would set up a service provider for view composers, with a closure-based composer that will apply to every page (the * wildcard symbol):
<?php namespace App\Providers;
use View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider {
/**
* Register bindings in the container.
*
* #return void
*/
public function boot()
{
View::composer('*', function($view)
{
//
});
}
/**
* Register
*
* #return void
*/
public function register()
{
//
}
}
Then you'll need to add the service provider to the providers array in config/app.php. This will register this service provider so that the view composer is called on every page load.
Then you can bind a collection of all Categories to all views by adding it to the wildcard view composer like so:
public function boot()
{
View::composer('*', function($view)
{
$view->with('categories', \App\Categories::all());
});
}
One solution is to use Laravel View Composers to bind data to a view.
all, what #jakeOpena says is true, View Composers is the best solution.
here is my example from route.php :
View::composer('layouts.left_navbar_menu', function($view) {
$menu = App::make('LeftNavMenu')->menuBilder();
$view->with('name', $menu);
});
my view "layouts/left_navbar_menu" is included in master template, like this:
#include('layouts.boot_left_navbar_menu')

Categories