How to use diffForHumans() with laravel view - laravel

I need to use diffForHumans() function in laravel blade file
I have use a data array to echo the data in blade view {{$data['time']}}
{{$data['time']}}
i expect the out is 2 minutes ago .

You can do the following:
// in your view add this
{{ Carbon\Carbon::parse($data['time'])->diffForHumans() }}
// or when you prepare your $data array in the controller or wherever
$data['time'] = $model->created_at->diffForHumans();

if the $data['time'] is an instance of carbon u can basically do {{$data['time']->diffForHumans()}}

Related

Laravel Blade Template - Put php built-function or maybe laravel helper inside yield

do you ever use PHP built-in function inside blade yield ?
For example can we do something like this :
// master layouts
#yield(ucwords('title'))
// view
#section('title', $title)
Note: $title is from controller
I've already try the first example, but it doesn't work. It doesn't output the $title on my view. Right now I am using this in all of my views
// master layouts
#yield('title')
// view 1
#section('title', ucwords($title))
// view 2
#section('title', ucwords($title))
// view 3
#section('title', ucwords($title))
But I think on second example, I'm not DRY my code because I always repeating the ucwords() on each my view. Can we using it on master layout right on yield declaration?
Thank you guys, have a nice work!
You can make your own blade directive for example if you want to make a #ucfirst() then do something like this in AppServiceProvider .
Blade::directive('ucfirst', function ($expression) {
return ucfirst($expression);
});
Past this into boot()
or on each section() you can extend the main layout #section('title', ucwords($title)) or make the helpers like i mentioned above
as you mentioned above you can use yield()
#yield('title',ucwords(strtolower('Your title')))

how to add common variable for laravel and pass this data to all view all views

I want to create a global variable and pass this into all view, so I can get this variable into all blade template
basically, my need is to pass my general setting controller value into my common blade view like header.blade.php
Thanks in advance
For that you will need to add some code in the App->Providers->AppServiceProvider.php like this:
public function boot()
{
view()->composer('*',function($view){
$settings = Settings::firstOrNew(['id' => '1']);
$view->with('settings', $settings );
});
}
According to Laravel documentation you can use view composer:
https://laravel.com/docs/5.8/views#view-composers
for using this feature in app > AppServiceProvider and in boot method you can use this approach for passing parameter to specific view If you have data that you want to be bound to a view each time that view is rendered. this approach meet your need perfectly. for example you want to pass a parameter named userName to header.
View()->composer('header', function ($view){
$userName= "username"
$view->with(['userName'=>$userName]);
});

How to call helper function in laravel 5.5

I am using laravel 5.5. I have created a helper.php in app\Http. I am calling this helper in my blade file by using
{!! Helper::functionName() !!}
this is working fine. but i want to hold this helper result in a variable like
{!! $Result=Helper::functionName() !!}
But currently this is printing this result. How to solve this. please help.
So that i can make any if condition on this $Result.
In my helpers.php
namespace App\Http\Helpers;
class Helper
{
public static function functionName()
{
return "mydata";
}
}
There is no point to use helper like this. You should run the helper in controller and pass calculated data into view. In most cases you shouldn't set any variables in views or make any calculations - those should be passed from controller to view and view should only use them.
In this case, you can use "<?php ?>".
So result:
<?php $Result=Helper::functionName(); ?>
may be this is not possible because in laravel "{{}}" this means echo "" so by default it will print the value. return the value from helper function and use in your blade

Create data to be outputted in a view?

In my view I output data from my database in the view via:
{{ $data->id }}
In one particular view I need do not get the data from a database but need to keep the view the same and manually set the id.
I've tried setting the id in my controller like:
$data['id'=>1];
But this fails to output in the view with:
{{ $data->id }}
Where am I going wrong?
You would want:
$data = new stdClass();
$data->id = 1;
Creating something like that will create an object (like an array, but accessed with $data->id instead of $data['id'].
To make your code simpler, Laravel has magic getters which means you can use $data['id'] in your view for data from the database. Then, when not using the database, you could do $data['id'] = 1; in your code rather than the two lines above.

Laravel Pagination links not including other GET parameters

I am using Eloquent together with Laravel 4's Pagination class.
Problem: When there are some GET parameters in the URL, eg: http://site.example/users?gender=female&body=hot, the pagination links produced only contain the page parameter and nothing else.
Blade Template
{{ $users->link() }}
There's a ->append() function for this, but when we don't know how many of the GET parameters are there, how can we use append() to include the other GET parameters in the paginated links without a whole chunk of if code messing up our blade template?
I think you should use this code in Laravel version 5+.
Also this will work not only with parameter page but also with any other parameter(s):
$users->appends(request()->input())->links();
Personally, I try to avoid using Facades as much as I can. Using global helper functions is less code and much elegant.
UPDATE:
Do not use Input Facade as it is deprecated in Laravel v6+
EDIT: Connor's comment with Mehdi's answer are required to make this work. Thanks to both for their clarifications.
->appends() can accept an array as a parameter, you could pass Input::except('page'), that should do the trick.
Example:
return view('manage/users', [
'users' => $users->appends(Input::except('page'))
]);
You could use
->appends(request()->query())
Example in the Controller:
$users = User::search()->order()->with('type:id,name')
->paginate(30)
->appends(request()->query());
return view('users.index', compact('users'));
Example in the View:
{{ $users->appends(request()->query())->links() }}
Be aware of the Input::all() , it will Include the previous ?page= values again and again in each page you open !
for example if you are in ?page=1 and you open the next page, it will open ?page=1&page=2 So the last value page takes will be the page you see ! not the page you want to see
Solution : use Input::except(array('page'))
Laravel 7.x and above has added new method to paginator:
->withQueryString()
So you can use it like:
{{ $users->withQueryString()->links() }}
For laravel below 7.x use:
{{ $users->appends(request()->query())->links() }}
Not append() but appends()
So, right answer is:
{!! $records->appends(Input::except('page'))->links() !!}
LARAVEL 5
The view must contain something like:
{!! $myItems->appends(Input::except('page'))->render() !!}
Use this construction, to keep all input params but page
{!! $myItems->appends(Request::capture()->except('page'))->render() !!}
Why?
1) you strip down everything that added to request like that
$request->request->add(['variable' => 123]);
2) you don't need $request as input parameter for the function
3) you are excluding "page"
PS) and it works for Laravel 5.1
In Your controller after pagination add withQueryString() like below
$post = Post::paginate(10)->withQueryString();
Include This In Your View
Page
$users->appends(Input::except('page'))
for who one in laravel 5 or greater
in blade:
{{ $table->appends(['id' => $something ])->links() }}
you can get the passed item with
$passed_item=$request->id;
test it with
dd($passed_item);
you must get $something value
In Laravel 7.x you can use it like this:
{{ $results->withQueryString()->links() }}
Pass the page number for pagination as well. Some thing like this
$currentPg = Input::get('page') ? Input::get('page') : '1';
$boards = Cache::remember('boards' . $currentPg, 60, function() {
return WhatEverModel::paginate(15);
});
Many solution here mention using Input...
Input has been removed in Laravel 6, 7, 8
Use Request instead.
Here's the blade statement that worked in my Laravel 8 project:
{{$data->appends(Request::except('page'))->links()}}
Where $data is the PHP object containing the paginated data.
Thanks to Alexandre Danault who pointed this out in this comment.

Resources