Laravel - Get the View name based on full path of the file - laravel

I wonder if I can get the View name based on full path of the view file.
Code example (expectation code):
$full_path = "D:\laragon\www\my-laravel-app\resources\views\user\login.blade.php";
$view_name = get_view_name($full_path);
echo $view_name;
// My expectation result should be $view_name = "user.login";
//
// So, it should echo this ---> user.login
Can I achieve this?
Thanks

I just got a solution.
function get_view_name($full_path){
$view_root_path = config('view.paths')[0];
$view_name = strtr($full_path, [
$view_root_path.'/' => '',
'.blade.php' => '',
'/' => '.',
]);
return $view_name;
}
But I think this is quite dirty solution.
So, I still hope if someone else got better and clean solution.
Thanks.

You can get name of route by using this
$request->route()->getName();
Or if you don't have $request where you want name of route you can achieve this with Request class
use Illuminate\Http\Request
Request::route()->getName();

Related

Get last part of current URL in Laravel 5 using Blade

How to get the last part of the current URL without the / sign, dynamically?
For example:
In www.news.com/foo/bar get bar.
In www.news.com/foo/bar/fun get fun.
Where to put the function or how to implement this in the current view?
Of course there is always the Laravel way:
request()->segment(count(request()->segments()))
You can use Laravel's helper function last. Like so:
last(request()->segments())
This is how I did it:
{{ collect(request()->segments())->last() }}
Use basename() along with Request::path().
basename(request()->path())
You should be able to call that from anywhere in your code since request() is a global helper function in Laravel and basename() is a standard PHP function which is also available globally.
The Route object is the source of the information you want. There are a few ways that you can get the information and most of them involve passing something to your view. I strongly suggest not doing the work within the blade as this is what controller actions are for.
Passing a value to the blade
The easiest way is to make the last part of the route a parameter and pass that value to the view.
// app/Http/routes.php
Route::get('/test/{uri_tail}', function ($uri_tail) {
return view('example')->with('uri_tail', $uri_tail);
});
// resources/views/example.blade.php
The last part of the route URI is <b>{{ $uri_tail }}</b>.
Avoiding route parameters requires a little more work.
// app/Http/routes.php
Route::get('/test/uri-tail', function (Illuminate\Http\Request $request) {
$route = $request->route();
$uri_path = $route->getPath();
$uri_parts = explode('/', $uri_path);
$uri_tail = end($uri_parts);
return view('example2')->with('uri_tail', $uri_tail);
});
// resources/views/example2.blade.php
The last part of the route URI is <b>{{ $uri_tail }}</b>.
Doing it all in the blade using the request helper.
// app/Http/routes.php
Route::get('/test/uri-tail', function () {
return view('example3');
});
// resources/views/example3.blade.php
The last part of the route URI is <b>{{ array_slice(explode('/', request()->route()->getPath()), -1, 1) }}</b>.
Try request()->segment($number) it should give you a segment of the URL.
In your example, it should probably be request()->segment(2) or request()->segment(3) based on the number of segments the URL has.
YourControllor:
use Illuminate\Support\Facades\URL;
file.blade.php:
echo basename(URL::current());
It was useful for me:
request()->path()
from www.test.site/news
get -> news
I just had the same question. In the meantime Laravel 8. I have summarised all the possibilities I know.
You can test it in your web route:
http(s)://127.0.0.1:8000/bar/foo || baz
http(s)://127.0.0.1:8000/bar/bar1/foo || baz
Route::get('/foo/{lastPart}', function(\Illuminate\Http\Request $request, $lastPart) {
dd(
[
'q' => request()->segment(count(request()->segments())),
'b' => collect(request()->segments())->last(),
'c' => basename(request()->path()),
'd' => substr( strrchr(request()->path(), '/'), 1),
'e' => $lastPart,
]
)->where('lastPart', 'foo,baz'); // the condition is only to limit
I prefer the variant e).
As #Qevo had already written in his answer. You simply make the last part part of the request. To narrow it down you can put the WHERE condition at the route.
Try with:
{{ array_pop(explode('/',$_SERVER['REQUEST_URI'])) }}
It should work well.

Laravel 5.2 HTTPNOTFOUNDEXCEPTION

I cant figure out what is causing this error. I have checked to see if the parameters are correct and they seem to be. Also if anybody has an alternative way to get all the parameters in the route rather than listing them all please do tell. I can't find another way.
public function savePaymentDetails(Request $request, $code, $message, $mPAN, $type, $exp, $name, $TxnGUID,
$ApprovalCode, $CVVMatch, $GT_MID, $GT_TRANS_ID, $GT_Val_Code, $ProcTxnID,
$session, $card_brand_selected, $CRE_Verbose_Request, $CRESecureID,
$trans_type, $content_template_url, $allowed_types, $order_desc, $sess_id,
$sess_name, $return_url, $total_amt, $submit, $ip_address, $customer_lastname, $customer_firstname)
{
$code2 = $request->get('code');
echo $code2;
echo $code;
}
The route
Route::get('return/{code}/{message}/{mPAN}/{type}/{exp}/{name}/{TxnGUID}/{ApprovalCode}/{CVVMatch}/{GT_MID}/{GT_Trans_Id
}/{GT_Val_Code}/{ProcTxnID}/{session}/{card_brand_selected}/{CRE_Verbose_Request}/{CRESecureID }/{trans_type}/{content_template_url}/{allowed_types}/{order_desc}/{sess_id}/{sess_name}/{return_url}/{total_amt
}/{submit}/{ip_address}/{customer_lastname}/{customer_firstname}', 'PaymentController#savePaymentDetails');
Here are the parameters returned by the URL that I need to get
/return?code=000&message=Success&mPAN=XXXXXXXXXXXX1111&type=Visa&exp=1218&name=test+visa&TxnGUID=6041323& ApprovalCode=VI0151&CVVMatch=M&GT_MID=672840408068703&GT_Trans_Id=016142173277748&GT_Val_Code=AACA&ProcTxnID=6041323&session=e91dd8af53j35k072s0bubjtn7&card_brand_selected=Visa&CRE_Verbose_Request=1&CRESecureID=gt153545888233SB&trans_type=+2&content_template_url=https%3A%2F%2Fexample.com%2Fpublic%2Ftemplate&allowed_types=Visa|MasterCard|American+Express&order_desc=6&sess_id=e91dd8af53j35k072s0bubjtn7&sess_name=session&return_url=https%3A%2F%2Fexample.com%2Fpublic%2Freturn&total_amt=1.51&submit=submit&ip_address=10.108.231.98&customer_lastname=visa&customer_firstname=test
The route rule you define actually match the url like this
code/message/mPAN/type/exp/name/TxnGUID/ApprovalCode/CVVMatch/GT_MID/GT_Val_Code/ProcTxnID/session/card_brand_selected/CRE_Verbose_Request/trans_type/content_template_url/allowed_types/order_desc/sess_id/sess_name/return_url/submit/ip_address/customer_lastname/customer_firstname
instead of
return?code=blab&blablabal=blab
You url dismatch any route you define , so a not found exception was thrown .
If you are trying to get all url parameters you can just write your route like that .
Route::get('return', 'PaymentController#savePaymentDetails');
And get parameters in your controller :
$parameters = $requests->all();
What's more , if you are trying to save something to your database , you'd better use the post method , you can find more When should i use post or get.

Laravel routing - shorten the urls upto only one URI segment.

It is said that shorter the URL, better the seo (atleast my client believes on it).
Now am creating website similar to watchtown.co.uk in laravel. I need to generate in such a way that the uri should not be more than one segment.
Requirement
I have following urls:
1.Need to change From:
localhost/laravelproj/public/brands/brandname/watches
to
localhost/laravelproj/public/brandname-watches.html
2.Need to change From:
localhost/laravelproj/public/brands/brandname/jewellery
to
localhost/laravelproj/public/brandname-jewellery.html
3.Need to change From:
localhost/laravelproj/public/categories/categoryname/watches
to
localhost/laravelproj/public/categoryname-watches.html
4.Need to change From:
localhost/laravelproj/public/categories/categoryname/jewellery
to
localhost/laravelproj/public/categoryname-jewellery.html
5.Need to change From:
localhost/laravelproj/public/products/productname
to
localhost/laravelproj/public/productname-watches.html
I hope you understood the pattern .
I can see watchtown.co.uk has done exactly the same (or is it any other way ?)
I created this function in controller for brands:
public function showProductListingByBrands($brandSlug) {
$brand = Brand::findBySlug($brandSlug)->first();
$products = "";
if($brand){
$products = $brand->products()->paginate(Misc::getSetting('paginate'));
}
$products = Product::findBySlug($brandSlug);
return View::make('store');
}
Now how do i manipulate it as my requirement? Im really new in laravel.
Thanks in advance.
Just to give you a brief idea.
On your route page
Route::get('/{product_name}/', array(
'as' => 'product_page',
'uses' => 'ProductPage#getProduct'
));
As you see when the user goes to the page like
Example: www.website.com/watch
it will go to the controller ProductPage with the method of getProduct, so the variable {product_name} will be passed on the controller.
Controller
public function getProduct($product_name = false) {
$product = Products::where('product_name', '=', $product_name);
// Do check product existing record
if ($product->count() == 0) {
return Redirect::route('some-page-error')
->with('failure', 'The hell are you doing?');
} else {
$product = $product->first();
return View::make('product_page')
->with('product_name', $product);
}
}
So on method getProduct, the parameter $product_name is watch
So, the method will check if the product exists or not, if not the user will be redirected to 404 page.
If not, it will be redirected to the template that you've made then pass all the product data and display it all there.
But it would be nice if you put the Route into /product/{product_name}, also it would be also good if it's product id instead of product name since product name can get redundant.
So yea.
edits
I don't know what you're trying to do and why it must be .html, but mmm.. Just wanna give you an idea. Well I don't know if my answer is a good way, someone might give better answer than me.

codeigniter uri/router checking

I am using codeigniter and have a controller in which I assign some search criteria's to be stored in session like this:
$srchCriteria = array(
'stockCode'=>$this->input->post('srchScode'),
'qty'=>$this->input->post('srchQty'),
'class' => $this->router->fetch_class(),
'method' => $this->router->fetch_method(),
);
$this->session->set_userdata('srchCriteria',$srchCriteria);
And on basis of this criteria output is generated. Now I need to clear this criteria if the user navigates to another page other than this page. i.e every time the user visits the search page the search criteria should be cleared except for pagination. For this purpose I checked the class and method variables in core controller like this:
$srchCriteria = $this->session->userdata('srchCriteria');
$className = $this->router->fetch_class();
$methodName = $this->router->fetch_method();
if(!empty( $srchCriteria['class'] ) && !empty( $srchCriteria['method'] )){
if( ($srchCriteria['method'] != $methodName){
$this->session->set_userdata('srchCriteria',array());
}
}
But it is not working please guide me in right way. What is my mistake here?
Try $this->session->unset_userdata('srchCriteria'); instead of $this->session->set_userdata('srchCriteria',array());

Symfony Routing: Can call route but not forward to

I have a route for just the locale without any other information (the startpage that is):
homepage:
pattern: /{_locale}/
defaults: { _controller: OurStartBundle:Default:index }
If I call the route directly it works (i.e.: localhost/de_DE/) but if I forward it throws the Error:
Unable to parse the controller name "/app_dev.php/de_DE/".
I forward using the Controller Method like this:
$locale = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
return $this->forward($this->generateUrl('homepage', array('_locale' => $locale)));
Anyone jave any idea why this doesn't work?
You are trying to forward the request to a URI, rather than a bundle string.
For example, your forward call should be...
$response = $this->forward('OurStartBundle:Default:index', array(
'_locale' => 'de_DE'
));
The Problem was that i used $this->forward() where i wanted a redirect and should have used $this->redirect().
Solution is:
$locale = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
return $this->redirect($this->generateUrl('OurStartBundle_homepage', array('_locale' => $locale)));

Resources