#foreach($users as $user)
$users[] = $user->name;
#endforeach
I want to get the output like this.
['X', 'Y', 'Z', 'C'];
Note: i need this because i have to use this in JavaScript function.
First of all, you can't "turn a foreach loop into an array", you would use that foreach loop to get an array as outcome. In this case I wouldn't go with a foreach approach, there are some methods that can help you cleaning out your code a bit.
You have two options depending on the type of the $users variable, pluck() or array_column():
// $users is a collection
json_encode($users->pluck('name'));
// $users is an array
json_encode(array_column($users, 'name'));
The json_encode() is highly recommended (as the comments pointed out) if you are going to use that output in your javascript. Now you can just send it in a respond and use it as a normal JSON.
In case you print the resulting variable using Blade, remember you need to use {!! !!}, otherwise, if you use {{ }} you would get unwanted scaped characters, since it uses htmlspecialchars() function under the hood.
Hope this helps you.
I recommend You should perform this action in your controller only, and then pass it to your view as
$userNames=implode(",",array_column($users,'name'));
return view('your_view',['userNames'=>$userNames]);
Then split it in your js as
var names="{!! $userNames!!}";
var names= names.split(",");
Collections will automatically be converted to json when you try to echo them.
The reason you're seeing " is because using {{ }} will automatically escape strings for your protection. You can prevent this by using {!! !!} instead.
Try something like this:
<script>
var data = '{!! $users->pluck('name') !!}';
console.log( JSON.parse(data));
</script>
Hope this helps!
Related
I've some html with {{ soimething }} placeholders in a table.
I would like to get the rendered view from this custom html.
I would like to avoid to manually do string replace.
Is it possible?
Note : I seen suggested questions but I ended finding a more concise way to reach my goal. So I post an answer to this question. Please keep this open.
You can use Blade Facade.
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Blade;
public function __invoke()
{
$name='Peter Pan';
return Blade::render("
<h1> Hello {$name} </h1>
",['name'=>$name]);
}
Found
We can use \Illuminate\View\Compilers\BladeCompiler::render($string, $data)
Where
$string is the text to parse, for example
Hi {{$username}}
$data is the same associate array we could normally pass down to view() helper, for example [ 'username' => $this->email ]
I was missing this from the official doc: https://laravel.com/docs/9.x/blade#rendering-inline-blade-templates
So we can also use
use Illuminate\Support\Facades\Blade;
Blade::render($string, $data)
Hello and thanks for your help. I've done some research and tried a few options but can't seem get this to work properly. I'm passing a URL with a query string into a function that loads the page via URL passed. However, I'm trying to find a way to paginate the results as well. Is there a way I can pass the query string url to Laravel's pagination links? Thanks.
My URL with query string
<a id="searchData"class="btn btn-primary ml-1 mr-5 text-light" title="Search" type="submit"
onclick="ajaxLoad('{{url('dma/data')}}?startDate='+$('#startDate').val()+'&endDate='+$('#endDate').val()
+ '&dmaNameFilter=' + encodeURI(dma_name) + '&memberNameFilter=' + encodeURI(member_name))">Search Results
</a>
I tried this for the links():
{{ $data->appends(request()->query())->links() }}
I have this in my Controller:
$data = Report::where('CallDate', '>=', $start_date)->where('CallDate', '<=', $end_date)->paginate(13)->appends(request()->query());
You can also add this:
$this->app->resolving(\Illuminate\Pagination\LengthAwarePaginator::class, function ($paginator) {
return $paginator->appends(Arr::except(request()->query(), $paginator->getPageName()));
});
To your AppServiceProvider
Try This
$data->appends(request()->input())->links()
You can pass any data to pagination by calling
{{ $paginator->links('view.name', ['foo' => 'bar']) }}
on your situation I think you want to pass query string to paginator; you may try
{{ $paginator->links('view.name', request()->getQueryString() ) }}
If you need to append querystrings for your ajax controller you'd better check https://github.com/spatie/laravel-query-builder
Since Laravel 8, You can simply use
$paginator->withQueryString();
I'd like to store a Customer model in a JS variable as JSON. Here are the approaches I tried and the pitfalls I found in each of them:
{{ $customer }} makes the resulting code in <script> look like this: var customer = {"id":1, ... "}, failing with Uncaught SyntaxError: Unexpected token & error. Also, if the variable is null in PHP, then in JS it becomes var customer = ;, which breaks the code.
{!! $customer !}} stores the data properly var customer = {"id":101, ... }, but it suffers from the same problem as {{ }} above when the variable is null in PHP.
{!! json_encode($customers->toArray()) !!}; works for a collection, but not for a single model object -- in the latter case PHP would fail by trying to call toArray() on null. Also, {!! !!} are vulnerable to XSS attacks.
The one that did work for me was {!! $customer ?? 'undefined' !!}. It properly handles all cases, but it's haky and insecure. Another solution seems to be {!! json_encode($customer) !!} but again, it also suffers from security issues. I wonder if it can be simplified to just {{ }}, or maybe there is a better approach.
Thanks!
Well that's a little difficult I was trying that time ago, but the only thing that I did (is not the better approach) is this...
I asssigned the values into data tags example
<input type="hidden" data-customer="{{json_encode(custumer)}}">
Then I used javascript/JQuery to access to tha info in my script
try isset
#if(isset($custumer)){{ $custumer }}#endif
I'm using this package, which does the magic for you:
https://github.com/laracasts/PHP-Vars-To-Js-Transformer
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.
I am new to codeigniter, i am simple datagrid with few columns.... what i want from grid is...i need get checked values from grid,....so i dont know how use foreach loop and get the values..
can any one explain me with example plz....
foreach ($persons as $person)
{
$this->table->add_row(form_checkbox('att',$person->tab_classid), $person->tab_classid, $person->tab_classtitle, date('d-m-Y H:i',strtotime($person->tab_classtime)),$person->tab_pemail,anchor($person->tab_prsturl,'view','target="_new"'),anchor($person->tab_recurl,'view','target="_new"'),$person->tab_classduration,$person->tab_crtdate,
anchor('person/view/'.$person->tab_classid,'view',array('class'=>'view')).' '.
anchor('person/update/'.$person->tab_classid,'update',array('class'=>'update')).' '.
anchor('person/test/'.$person->tab_classid,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$person->tab_classid,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))
);
}
$data['table'] = $this->table->generate();
PHP is best for processing server code but what you are looking for is tend to be of client side analyses. I suggest you do this sort of check by javascript/jquery instead.
Leave/process this in an each(function(){...});
var check=$('chkboxId').attr('checked').value;