CodeIgniter -> Get current URL relative to base url - codeigniter

Tried URI::uri_string() but can't get it to work with the base_url.
URL: http://localhost/dropbox/derrek/shopredux/ahahaha/hihihi
Returns: dropbox/derrek/shopredux/ahahaha/hihihi
but http://localhost/dropbox/derrek/shopredux/ just returns an empty string.
I want the first call to return "ahahaha/hihihi" and the second to return "". Is there such a function?

// For current url
echo base_url(uri_string());

If url helper is loaded, use
current_url();
will be better

Try to use "uri" segments like:
$this->uri->segment(5); //To get 'ahahaha'
$this->uri->segment(6); //To get 'hihihi
form your first URL...You get '' from second URl also for segment(5),segment(6) also because they are empty.
Every segment function counts starts form localhost as '1' and symultaneous segments

For the parameter or without parameter URLs Use this :
Method 1:
$currentURL = current_url(); //for simple URL
$params = $_SERVER['QUERY_STRING']; //for parameters
$fullURL = $currentURL . '?' . $params; //full URL with parameter
Method 2:
$full_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
Method 3:
base_url(uri_string());

I see that this post is old. But in version CI v3 here is the answer:
echo $this->uri->uri_string();
Thanks

//if you want to get parameter from url use:
parse_str($_SERVER['QUERY_STRING'], $_GET);
//then you can use:
if(isset($_GET["par"])){
echo $_GET["par"];
}
//if you want to get current page url use:
$current_url = current_url();

Running Latest Code Igniter 3.10
$this->load->helper('uri'); // or you can autoload it in config
print base_url($this->uri->uri_string());

I don't know if there is such a function, but with $this->uri->uri_to_assoc() you get an associative array from the $_GET parameters.
With this, and the controller you are in, you know how the URL looks like.
In you above URL this would mean you would be in the controller dropbox and the array would be something like this:
array("derrek" => "shopredux", "ahahaha" => "hihihi");
With this you should be able to make such a function on your own.

In CI v3, you can try:
function partial_uri($start = 0) {
return join('/',array_slice(get_instance()->uri->segment_array(), $start));
}
This will drop the number of URL segments specified by the $start argument. If your URL is http://localhost/dropbox/derrek/shopredux/ahahaha/hihihi, then:
partial_uri(3); # returns "ahahaha/hihihi"

you can use the some Codeigniter functions and some core functions and make combination to achieve your URL with query string.
I found solution of this problem.
base_url($this->uri->uri_string()).strrchr($_SERVER['REQUEST_URI'], "?");
and if you loaded URL helper so you can also do this current_url().strrchr($_SERVER['REQUEST_URI'], "?");

<?php $currentMenu = $this->uri->segment(2); ?>
<ul>
<li class="nav-item <?= ($currentMenu == 'dashboard') ? 'active' : '' ?>">
<a href="<?= site_url('/admin/dashboard'); ?>" class="nav-link"><i data-
feather="pie-chart"></i> Dashboard</a>
</li>
</ul
this is work for me

Related

How to catch if editor url is opened?

In laravel 8 app I select active menu item with
<a class="nav-main-link {{ request()->is('admin/compilations') ? ' active_nav_menu' : '' }}"
and it works ok for link like :
http://127.0.0.1:8000/admin/compilations
But it does not work for link like :
http://127.0.0.1:8000/admin/compilations/2/edit
How can be fixed ?
Thanks in advance!
I think the cleanest solution for this is to gives your route names instead of hard-checking URL patterns (https://laravel.com/docs/8.x/routing#named-routes) and utilize one of the following methods:
$route = Route::current(); // Illuminate\Routing\Route
$name = Route::currentRouteName(); // string
$action = Route::currentRouteAction(); // string
If you have the $route instance you can also do something like $route->currentRouteNamed(...)
See full API here:
https://laravel.com/api/8.x/Illuminate/Routing/Router.html#method_getCurrentRoute

How to append query string to pagination links using Laravel

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

how construct route pattern for an unknown number of tags - Laravel & Conner/Taggable

I have a blog and a quotationfamous sayings repository on one site.
The quotations are tagged and the entries are tagged too.
I use this rtconner/laravel-tagging package.
Now, what I want to do is to display ALL Quotation models which share the same tags as article.
The Eloquent syntax is simple, as the original docs provide an example:
Article::withAnyTag(['Gardening','Cooking'])->get();
possible solution
Optional routing parameters. The asker-picked answer in this question gives a solution:
//in routes.php
Route::get('/{book?}/{chapter?}/{topic?}/{article?}', 'controller#func');
//in your controller
public function func($book = null, $chapter = null, $topic = null, $article = null) {
...
}
my problem
In my app the shared tags might count more than 3 or 5. I will soon get an example with even 10 tags. Possibly more
My question
Does it mean that I have to construct an URL with 10 optional routing parameters? Do I really need sth like this:
Route::get('quotations/tags/{tag1?}/{tag2?}/{tag3?}/{tag4?}/{tag5?}/{tag6?}/{tag7?}', 'controller#func');
my question rephrased
I could create a form with only a button visible, and in a hidden select field I could put all the tags. The route would be a POST type then and it would work. But this solution is not URL-based.
I think you could process the slashes, as data:
Route::get('quotations/tags/{tagsData?}', 'controller#func')
->where('tagsData', '(.*)');
Controller:
public function controller($tagsData = null)
{
if($tagsData)
{
//process
}
}
Ok, this is my solution. As I have a tagged model, I dont't need to iterate through tags in url to get the whole list of tags.
The enough is this:
// Routes file:
Route::get('quotations/all-tags-in/{itemtype}/{modelid}', 'QuotationsController#all_tagged_in_model');
Then in my controller:
public function all_tagged_in_topic($itemtype, $id) {
if($itemtype == 'topic') {
$tags = Topic::find($id)->tags->pluck('name')->all();
$topic = Topic::find($id);
}
if($itemtype == 'quotation') {
$tags = Quotation::find($id)->tags->pluck('name')->all();
$quotation = Quotation::find($id);
}
// dd($tags);
$object = Quotation::withAnyTag($tags)->paginate(100);;
And it is done.
Now, the last issue is to show tags in the URL.
TO do that, the URL should have an extra OPTIONAL parameter tags:
// Routes file:
Route::get('quotations/all-tags-in/{itemtype}/{modelid}/{tags?}', 'QuotationsController#all_tagged_in_model');
And in the {url?} part you can just write anything which won't break the pattern accepted by route definition.
In your view you might generate an URL like this:
// A button to show quotes with the same set of tags as the article
// generated by iteration through `$o->tags`
<?php
$manual_slug = 'tag1-tag2-tag3-tag4`;
?>
<a href="{{ URL::to('quotations/all-tags-in/article/'.$o->id.'/'.$manual_slug) }}" class="btn btn-danger btn-sm" target="_blank">
<i class="fa fa-tags icon"></i> Tagi:
</a>

Add parameter to Codeigniter URL

I have a problem when i try to add other parameter to URL.
before i use Codeigniter i add those parameters using JavaScript like this
test
but when i tried to do it with Codeigniter i don't know how.
<?php echo anchor("home/index/param1","test"); ?>
as i said i want to add this parameter for example my URL looks like this
home/index/param2
so when i click on test i want the URL to be like this
home/index/param2/param1
Take a look at CodeIgniter's URL Helper Documentation
The first parameter can contain any segments you wish appended to the URL. As with the site_url() function above, segments can be a string or an array.
For your example, you could try:
<?php
$base_url = 'home/index/';
$param1 = 'param1';
$param2 = 'param2';
$segments = array($base_url, $param1, $param2);
echo anchor($segments,"test");
?>
You can't do that with the form helper, you have to use your js function again :
echo anchor("home/index/param2", "test", array("onClick" => "javascript:addParam(window.location.href, 'display', 'param1');"));
It will produce :
test
But I don't see the point of dynamically change the href on the click event. Why don't you set it directly at the beginning ?
echo anchor("home/index/param2/param1", "test");

CodeIgniter adjusting url when passing parameters to controler

Ok i have records from database listed in view file, so u can see i wanna pass values to controler via href by update/grab function controler
echo $this->pagination->create_links();
br().br();
foreach ($query->result() as $q): ?>
<?php echo $q->info . br()?>
<?php endforeach; ?>
it works for first page in my pagination, when i am on some other page when i clicked on on record, instead passing parametars to controler when i clicked in keep adding url for example http://localhost/z/records/users/update/grab/3/update/grab/1/update/grab/1/update/grab/1/trtr
So error is when i have in url, when i am on second page in pagination
http://localhost/z/records/users/2
works only when i am on first page
http://localhost/z/records
is there a way to solve this proble. Will it works if i some how adjust routes??? Need help, please help me its very important
Try changing your link to an absolute URL:
<a href="/z/update/grab/<?php echo $q->id;?>/<?php echo $q->info; ?>">
Or adding a correct relative URL base to the header of your pages:
<base href="/z/" />
Codeigniter routes allow you to do this:
$route['post/(:any)/comment/(:any)'] = "posts/comments/$1/$2";
Then in the controller, the function inside my posts controller would work like this:
public function comments($one, $two) {
echo $one."-".$two;
}
so if you hit the url "/post/111/comment/222" the output would be
111-222

Resources