Laravel dynamic routing for search - laravel

I would like to generate dynamic route when user clicks on Search button.
I know it can be done with following GET method
https://laravel.dev/search?q=parameter
https://laravel.dev/search?state=XYZ&category=Automobile
But instead I would like to do following
https://laravel.dev/search/state/XYZ/category/Automobile
So if I add an extra parameter in search form it will just add onto the URL.
The parameters may be optional so can not add a fix route in routes. User may supply state or search through all states.
https://laravel.dev/search/category/Automobile
Following is my search form code
<div class="jumbotron">
<!--Search Bar-->
{{ html()->form('GET',route('frontend.search'))->class('form-inline justify-content-center')->open() }}
{{ html()->select('category',$categories)->class('form-control mr-sm-2') }}
{{ html()->select('state',$states)->class('form-control mr-sm-2') }}
<!--More filter to add later-->
<button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
{{ html()->form()->close() }}
</div>
How can I achieve that?
Thank you

You can handle the logic with a catch-all route with regular expressions
https://laravel.com/docs/7.x/routing#parameters-regular-expression-constraints
//routes.php
Route::get('search/{search?}', 'SearchController#search')
->where('search', '(.*)');
//controller
class SearchController extends BaseController {
public function search($search = null)
{
if ($search != null){
dd($search);
}
}
}

Try to use Regex:
Route::get('search/{searchParams}', 'SearchController#search')
->where('searchParams', '[a-zA-Z0-9\/]+');
You can put anything on searchParams but you need to parse it.

Related

Check wildcard routes in Laravel 5

In blade, If we want to check that the current route matches with a route or not, we can simply use:
#if(Route::currentRouteName() == 'parameter')
{{ 'yes' }}
#else
{{ 'no' }}
#endif
But what if we want to match it with a wildcard like:
#if(Route::currentRouteName() == 'parameter.*')
{{ 'yes' }}
#else
{{ 'no' }}
#endif
Is there any solution for that?
I have tried "*" and ":any", but it didn't work.
Note: I want to check route, not URL.
Any help would be appreciated.
Thanks,
Parth Vora
Use Laravel's string helper function
str_is('parameter*', Route::currentRouteName())
It'll return true for any string that starts with parameter
I had the same problem. I wanted to toggle an active class based on a URI.
In blade (Laravel 6x), I did:
(request()->is('projects/*')) ? 'active' : ''
You can also make use of Blades Custom If Statements and write something like this in your AppServiceProvider.php:
public function boot()
{
Blade::if('route', function ($route) {
return Str::is($route, Route::currentRouteName());
});
}
then you can use it in a blade view like this:
<li #route('admin.users*') class="active" #endroute>
Users
</li>

can I use route() to make a DELETE request in laravel

I'm using laravel and trying to delete something. Is it possible to specify the DELETE method on laravel's route()??
e.g
route('dashboard-delete-user', ['id' => $use->id, 'method'=> 'delete'])
or something like that??
EDIT:
What I meant was could I specify that in a link or a button in my blade template. Similar to this:
href="{{ route('dashboard-delete-user') }}
Yes, you can do this:
Route::delete($uri, $callback);
https://laravel.com/docs/master/routing#basic-routing
Update
If for some reason you want to use route only (without a controller), you can use closure, something like:
Route::get('delete-user/{id}', function ($id) {
App\User::destroy($id);
return 'User '.$id.' deleted';
});
No or at least I haven't figure out how to.
The only way for this to work out of the box would be to build a form to handle it. At the very minimum, you would need...
<form action="{{ route('dashboard-delete-user') }}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type="submit" value="submit">Submit</button>
</form>
Or you can just create the get route which you are trying to link to and have it handle the logic. It doesn't need to be a route which only respondes to delete requests to delete a resource.
Yes you can, using a URL helper. https://laravel.com/docs/5.2/helpers#urls
There are several options to choose from.

laravel passing parameters from view to route

Using a view with user input. I then want to pass to a route. This what I found so far:
href="{{URL::to('customers/single'$params')}}"
I want to pass the user input as the above $params to my route. This is sample of my route:
Route::get('customer/{id}', function($id) {
$customer = Customer::find($id);
return View::make('customers/single')
->with('customer', $customer);
As soon as I can pass the parameter I can do what I want with the route, which I know how.
Basically you can pass parameter to routes by doing:
Route::get('user/{name}', function($name)
{
//
})
->where('name', '[A-Za-z]+');
In your anchor tag, instead of doing href={{URL...}}, do something like:
{{ URL::to('user/$param') }}
For more information on routing, visit link
This is what I have and works:
<a <button type="button" class="buttonSmall" id="customerView" href="{{URL::to('customer',array('id'=>'abf'))}}" >View</button></a>
But I need the array value 'abf' to be the value of a textbox.
This worked for me in my view anchor tag
href="{{ URL::to('user/'.$param) }}"
instead of what was specified above
href="{{ URL::to('user/$param') }}"
You can user it in View as I used:
<a class="stocks_list" href="/profile/{{ Auth::user()->username }}">Profile</a>
Hope it helps you.

Laravel: delete photo by photo id

I'm trying to delete a photo by it's id, but the routes do not work and I receive a MethodNotAllowedHttpException. What I do:
First I create a form (in my blade template):
{{ Form::open(array("action" => array("cms/albums/destroyphoto", $photo['id']), "method" => "DELETE")) }}
<button type="submit">Delete</button>
{{ Form::close() }}
Then i create my route:
Route::post('cms/albums/destroyphoto/{id}', 'AlbumsController#destroyphoto');
And create my function in the Albumscontroller:
public function destroyphoto($id)
{
dd('Welcome photo');
}
Any suggestions where the routing goes wrong?
Thanks in advance.
Ps. I did composer dump-autoload
When you open your form using "action" you should pass the controller class and action name. You also don't need to specify the method since you're using Route::post
Like this:
{{ Form::open(array("action" => array("AlbumsController#destroyphoto", $photo['id']))) }}
More information

How to Get the Current URL Inside #if Statement (Blade) in Laravel 4?

I am using Laravel 4. I would like to access the current URL inside an #if condition in a view using the Laravel's Blade templating engine but I don't know how to do it.
I know that it can be done using something like <?php echo URL::current(); ?> but It's not possible inside an #if blade statement.
Any suggestions?
You can use: Request::url() to obtain the current URL, here is an example:
#if(Request::url() === 'your url here')
// code
#endif
Laravel offers a method to find out, whether the URL matches a pattern or not
if (Request::is('admin/*'))
{
// code
}
Check the related documentation to obtain different request information: http://laravel.com/docs/requests#request-information
You can also use Route::current()->getName() to check your route name.
Example: routes.php
Route::get('test', ['as'=>'testing', function() {
return View::make('test');
}]);
View:
#if(Route::current()->getName() == 'testing')
Hello This is testing
#endif
Maybe you should try this:
<li class="{{ Request::is('admin/dashboard') ? 'active' : '' }}">Dashboard</li>
To get current url in blade view you can use following,
Current Url
So as you can compare using following code,
#if (url()->current() == 'you url')
//stuff you want to perform
#endif
I'd do it this way:
#if (Request::path() == '/view')
// code
#endif
where '/view' is view name in routes.php.
This is helped to me for bootstrap active nav class in Laravel 5.2:
<li class="{{ Request::path() == '/' ? 'active' : '' }}">Home</li>
<li class="{{ Request::path() == 'about' ? 'active' : '' }}">About</li>
A little old but this works in L5:
<li class="{{ Request::is('mycategory/', '*') ? 'active' : ''}}">
This captures both /mycategory and /mycategory/slug
Laravel 5.4
Global functions
#if (request()->is('/'))
<p>Is homepage</p>
#endif
You can use this code to get current URL:
echo url()->current();
echo url()->full();
I get this from Laravel documents.
I personally wouldn't try grabbing it inside of the view. I'm not amazing at Laravel, but I would imagine you'd need to send your route to a controller, and then within the controller, pass the variable (via an array) into your view, using something like $url = Request::url();.
One way of doing it anyway.
EDIT: Actually look at the method above, probably a better way.
You will get the url by using the below code.
For Example your URL like https//www.example.com/testurl?test
echo url()->current();
Result : https//www.example.com/testurl
echo url()->full();
Result: https//www.example.com/testurl?test
For me this works best:
class="{{url()->current() == route('dashboard') ? 'bg-gray-900 text-white' : 'text-gray-300'}}"
A simple navbar with bootstrap can be done as:
<li class="{{ Request::is('user/profile')? 'active': '' }}">
Profile
</li>
The simplest way is to use: Request::url();
But here is a complex way:
URL::to('/').'/'.Route::getCurrentRoute()->getPath();
There are two ways to do that:
<li{!!(Request::is('your_url')) ? ' class="active"' : '' !!}>
or
<li #if(Request::is('your_url'))class="active"#endif>
You should try this:
<b class="{{ Request::is('admin/login') ? 'active' : '' }}">Login Account Details</b>
The simplest way is
<li class="{{ Request::is('contacts/*') ? 'active' : '' }}">Dashboard</li>
This colud capture the contacts/, contacts/create, contacts/edit...
For named routes, I use:
#if(url()->current() == route('routeName')) class="current" #endif
Set this code to applied automatically for each <li> + you need to using HTMLBuilder library in your Laravel project
<script type="text/javascript">
$(document).ready(function(){
$('.list-group a[href="/{{Request::path()}}"]').addClass('active');
});
</script>
instead of using the URL::path() to check your current path location, you may want to consider the Route::currentRouteName() so just in case you update your path, you don't need to explore all your pages to update the path name again.
In Blade file
#if (Request::is('companies'))
Companies name
#endif
class="nav-link {{ \Route::current()->getName() == 'panel' ? 'active' : ''}}"
Another way to write if and else in Laravel using path
<p class="#if(Request::is('path/anotherPath/*')) className #else anotherClassName #endif" >
</p>
Hope it helps
Try this:
#if(collect(explode('/',\Illuminate\Http\Request::capture()->url()))->last() === 'yourURL')
<li class="pull-right"><a class="intermitente"><i class="glyphicon glyphicon-alert"></i></a></li>
#endif
For Laravel 5.5 +
<a class="{{ Request::segment(1) == 'activities' ? 'is-active' : ''}}" href="#">
<span class="icon">
<i class="fas fa-list-ol"></i>
</span>
Activities
</a>
1. Check if URL = X
Simply - you need to check if URL is exactly like X and then you show something. In Controller:
if (request()->is('companies')) {
// show companies menu or something
}
In Blade file - almost identical:
#if (request()->is('companies'))
Companies menu
#endif
2. Check if URL contains X
A little more complicated example - method Request::is() allows a pattern parameter, like this:
if (request()->is('companies/*')) {
// will match URL /companies/999 or /companies/create
}
3. Check route by its name
As you probably know, every route can be assigned to a name, in routes/web.php file it looks something like this:
Route::get('/companies', function () {
return view('companies');
})->name('comp');
So how can you check if current route is 'comp'? Relatively easy:
if (\Route::current()->getName() == 'comp') {
// We are on a correct route!
}
4. Check by routes names
If you are using routes by names, you can check if request matches routes name.
if (request()->routeIs('companies.*')) {
// will match routes which name starts with companies.
}
Or
request()->route()->named('profile')
Will match route named profile. So these are four ways to check current URL or route.
source
#if(request()->path()=='/path/another_path/*')
#endif
Try This:
<li class="{{ Request::is('Dashboard') ? 'active' : '' }}">
<a href="{{ url('/Dashboard') }}">
<i class="fa fa-dashboard"></i> <span>Dashboard</span>
</a>
</li>
There are many way to achieve, one from them I use always
Request::url()
Try this way :
registration

Resources