How to catch if editor url is opened? - laravel

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

Related

How do I get data from the Route and show it in a html page?

I am trying get a value from the URL for example : websitename.com/dash/namehere
I have route :
Route::get('/dash/{id}', 'DashController#index' , function($id) {
return 'dash'.$id;
});
Then I have a section on the page I am trying to display as a title. I am currently using this:
#if (\Request::is('dash/1'))
<div class="pagetitle">[clientname]</div>
#endif
This works but I am thinking there is a better way to approach this. I am very new to this.
I want to get the id from the url / site.com/dash/ {id} and use it in the HTML page as a Title header.
Use {{ request()->route('id') }} in your blade to get the "id" parameter from the dash route.

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>

Get Laravel 5 controller name in view

Our old website CSS was set up so that the body tag had an id of the controller name and a class of the action name, using Zend Framework 1. Now we're switching to Laravel 5. I found a way to get the action name through the Route class, but can't find a method for the controller name. I don't see anything in the Laravel docs like this. Any ideas?
This is how you do with action. You inject the Route class, and then call:
$route->getActionName().
I'm looking for something similar for controllers. I've checked the entire route class and found nothing.
If your layout is a Blade template, you could create a view composer that injects those variables into your layout. In app/Providers/AppServiceProvider.php add something like this:
public function boot()
{
app('view')->composer('layouts.master', function ($view) {
$action = app('request')->route()->getAction();
$controller = class_basename($action['controller']);
list($controller, $action) = explode('#', $controller);
$view->with(compact('controller', 'action'));
});
}
You will then have two variables available in your layout template: $controller and $action.
I use a simple solution. You can test and use it in everywhere, also in your views:
{{ dd(request()->route()->getAction()) }}
I will simply use as bellow
$request->route()->getActionMethod()
To get something like PostController try following ...
preg_match('/([a-z]*)#/i', $request->route()->getActionName(), $matches);
$controllerName = $matches[1];
$matches[1] includes the first group while $matches[0] includes everything matched. So also the # which isn't desired.
use this
strtok(substr(strrchr($request->route()->getActionName(), '\\'), 1), '#')
To add to Martin Bean answer, using Route::view in your routes will cause the list function to throw an Undefined offset error when this code runs;
list($controller, $action) = explode('#', $controller);
Instead use this, which assigns null to $action if not present
list($controller, $action) = array_pad(explode('#', $controller), 2, null);
You can use this to just simply display in the title like "Customer - My Site" (laravel 9)
{{ str_replace('Controller', '', strtok(substr(strrchr(request()->route()->getActionName(), '\\'), 1), '#'))}} - {{ config('app.name') }}
You can add this (tested with Laravel v7+)
<?php
use Illuminate\Support\Facades\Route;
echo Route::getCurrentRoute()->getActionMethod();
?>
or
You can use helper function
<?php echo request()->route()->getActionMethod(); ?>
for example :-
Route::get('test', [\App\Http\Controllers\ExampleController::class, 'exampleTest'])->name('testExample');
Now If I request {app_url}/test then it will return exampleTest

CodeIgniter -> Get current URL relative to base url

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

How do you use JRoute in Joomla to route to a Search menu item?

I am trying to create a a box in a template in Joomla! that will display all of the keywords and link them to their appropriate search page. I have a menu item set, however, I don't want to hard-code the menu item into the template, so I want to use the JRoute object to generate the SEF url.
I am using this function:
JRoute::_('index.php?option=com_search&searchword='.$keyword);
or this:
JRoute::_('index.php?option=com_search&view=search&searchword='.$keyword);
however, this generates a url like this:
/component/search/?searchword=africa
when it ought to create a search url like this:
/searchmenuitem?searchword=africa
I have searched extensivly online and havn't found a solution to this problem. Any ideas would be greatly appreciated.
Ok, so some additional information for you.. I am only experiencing the problem when I try and route the URL from a template in com_content. If I try and route the url from a template in com_search everything works perfectly. So, what is it about com_content that is causing this to not work properly?
thanks!
david
In joomla administration page go to the menu item you've chosen for the search results page and get the id of that menu item (itemId).
Than you can try using:
JRoute::_('index.php?option=com_search&view=search&Itemid=256&searchword=asdsadasdsa');
or even
JRoute::_('index.php?Itemid=256&searchword=asdsadasdsa');
both should result in: /searchmenuitem.html?searchword=asdsadasdsa
EDIT:
To make it more comforable you could add itemId as a param to your template.
There is another way, where u can get the itemId from the database (this method is required on multilingual websites). Let me know if you want it.
EDIT2:
Here it is:
$db =& JFactory::getDBO();
$lang =& JFactory::getLanguage()->getTag();
$uri = 'index.php?option=com_search&view=search';
$db->setQuery('SELECT id FROM #__menu WHERE link LIKE '. $db->Quote( $uri .'%' ) .' AND language='. $db->Quote($lang) .' LIMIT 1' );
$itemId = ($db->getErrorNum())? 0 : intval($db->loadResult());
I use this kind of method to get a menu item id of specific component and view
function getSearchItemId() {
$menu = &JSite::getMenu();
$component = &JComponentHelper::getComponent('com_search');
//get only com_search menu items
$items = $menu->getItems('componentid', $component->id);
foreach ($items as $item) {
if (isset($item->query['view']) && $item->query['view'] === 'search') {
return $item->id;
}
}
return false;
}
Then I use this method to get the sef url
function getRouteUrl($route)
{
jimport('joomla.application.router');
// Get the global site router.
$config = &JFactory::getConfig();
$router = JRouter::getInstance('site');
$router->setMode($config->getValue('sef', 1));
$uri = &$router->build($url);
$path = $uri->toString(array('path', 'query', 'fragment'));
return $path;
}
This just works in any template.
use like this
$itemid = getSearchItemId();
//returns valid sef url
$url = getRouteUrl('index.php?Itemid='.$itemid);
You really do not need to do sql on the menu table to get ids. Just search the menu object.
Try to create new menu in the joomla backend called for instance 'hidden-menu'. It will never be shown in the front. But it will be used by JRoute Then add to this menu new menuitem called 'searchmenuitem' with link to com_search. That is all. Now you can call
JRoute::_('index.php?option=com_search&view=search&searchword=asdsadasdsa');
and it will be ceonverted into this
/searchmenuitem.html?searchword=asdsadasdsa

Resources