LARAVEL 5.0
PHP 5.4.45
I have a route that is shaped like this :
/app/Http/routes.php
Route::get('/clients/search/{id}', 'ClientController#searchById')->where('id', '[0-9]+');
Route::get('/clients/search/{text}', 'ClientController#searchByText')->where('text', '[a-zA-Z]');
I will not print my view here but it simply search for the exact client (case id) or the first 10 clients (case text).
Then I want to create a search form. I created the route :
/app/Http/routes.php
// Route::get('/clients/search/{id}', 'ClientController#searchById')->where('id', '[0-9]+');
// Route::get('/clients/search/{text}', 'ClientController#searchByText')->where('text', '[a-zA-Z]');
Route::get( '/clients/search', 'ClientController#search');
The controller for this route :
/app/Http/Controllers/ClientController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class ClientController extends Controller {
// Controllers for the 'searchById' and 'searchByText'
public function search() {
return view('client.search.search', [
'title' => 'Client search form',
'title_sub' => ''
]);
}
}
And the view for this search form :
/ressources/view/client/search/search.blade.php
<form action="/clients/search/INPUT HERE ?" method="get">
<div class="input-group">
<input id="newpassword" class="form-control" type="text" name="password" placeholder="Id de client, nom, prénom, ...">
<span class="input-group-btn">
<button id="button_search" class="btn green-haze" type="submit"><i class="fa fa-search fa-fw"></i></button>
</span>
</div>
</form>
QUESTION
How can I, before submit, pass an input as a part of my action attribute for my form ? The point is to be able to launch those kind of requests :
/clients/search/26
/clients/search/Mike%20%Folley
/clients/search/Paris
So my controllers handling this route could do the job. Is there any way to do that ? Or should I go for JavaScript solution (which make me sad a bit) ?
Yes, you need javascript to modify request URL before it is even sent :). No form tag needed for that, vanilla js approach like this might be sufficient:
<input type="text" id="search">
<button onclick="search()">
Submit
</button>
<script>
function search() {
window.location='/search/' +
encodeURIComponent(document.getElementById('search').value);
}
</script>
You can and should just use one route and then in controller's method decide on what to search and what view to return. Routes should contain the least amount of logic possible.
Related
Hello i'm new in laravel. My application has a search bar component in almost every view.
The user types there the ID of the client, makes a query to db and compares the user's typed ID with the DB client ID.
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class SearchController extends Controller
{
function get_kcli(Request $request) {
$id = $request->input('kcli');
$current_page = $request->input('currentPage') . '.index';
$data = DB::connection('oracle')->table('CLIENTS')->where('KCLI', $id)->get();
return view($current_page, compact('data'));
}
}
Web.php
Route::post('/search', [App\Http\Controllers\SearchController::class, 'get_kcli'])->name('search');
Form search component view:
<nav class="navbar navbar-light">
<form method="POST" class="form-inline position-relative" action="{{ route('/search') }}">
#csrf
#method('POST')
<input class="form-control shadow-none" name="kcli" id="kcli" type="number" placeholder="Codice..." aria-label="Search">
<input type="text" name="currentPage" value="{{ Route::currentRouteName() }}" hidden>
<button type="submit" class="btn btn-light search-btn"><i class="fas fa-search"></i></button>
</form>
Anyone knows the best practice to store that data request globally an mantain it for every view that need to exctract it?
Example : I search for the client ID '5', the search controller makes a db query with the passed ID, then compacts data. That data has to be stored globally for get the results and post it in other views, without searching again on every view switch(the typed ID '5' has to remain in the search field on every view switch).
To print client_id you can store that "id" in session and print from the session by this way your search value keep remains and to get data in all views there is the concept View::share you can register that in AppServiceProvider please go through this link
https://laravel.com/docs/9.x/views#sharing-data-with-all-views
I created a model and its migration like this:
php artisan make:model Lala -m
And I made this : php artisan migrate
I was going to call this road, but I have a mistake. Did I write it wrong? How can I call the search method when my form is submitted?
formular:
<?php
use App\Models\Lala;
?>
<form action="{{ route('Lala.search')}}" method="GET" >
<div class="input-group mb-3">
<input type="text"
name="name" class="form-control" placeholder="Geben Sie etwas an"
aria-label="Geben Sie etwas an"
aria-describedby="basic-addon2" autocomplete="off">
<div class="input-group-append">
<span class="input-group-text" id="basic-addon2">🎓</span>
</div>
</div>
<input type="submit" class="btn btn-primary" value="search">
</form>
I defined the route as follows in web.php :
use App\Models\Lala;
Route::get('/search',[
'as' =>'Lala.search',
'uses' =>'\App\Http\Controllers\stipendiensController#search']);
stipendiensController is defined like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Stipendien;
class stipendientsController extends Controller
{
public $name;
public function search()
{
return view('seite.Stipendien');
}
}
how to avoid this error? could I write this code differently? I try indeed to enter the data in my search bar and I compare in my database if the value entered in the search bar is there.
Thank you for helping me . Please
Try defineing your route like so:
use App\Http\Controllers\stipendiensController;
Route::get('/search', [stipendiensController::class, 'search'])
->name('Lala.search');
I'm trying to do an image upload using Laravel livewire, but when I click on the button "upload" to test the functionality this error appears
The POST method is not supported for this route. Supported methods: GET, HEAD'
The programs:
ROUTE
Route::get('/upload', UploadFoto::class)->name('upload.foto.user');
CONTROLLER (using dd for the tests)
<?php
namespace App\Http\Livewire\User;
use Livewire\Component;
class UploadFoto extends Component
{
public $foto;
public function render()
{
return view('livewire.user.upload-foto');
}
public function storageFoto()
{
dd('aqui');
}
}
VIEW
#extends('layouts.app')
#section('content')
<div>
{{-- To attain knowledge, add things every day; To attain wisdom, subtract things every day. --}}
<form action="#" method="post">
<input type="file" name="foto" id="foto" wire:submit.prevent="storageFoto">
<button type="submit">Upload</button>
</form>
</div>
#endsection
You set get method on this route - but upload use post method. Change it:
Route::post('/upload', UploadFoto::class)->name('upload.foto.user');
please check this, you added submit in wrong place of form
<div>
<form wire:submit.prevent="storageFoto" method="post">
<input type="file" name="foto" id="foto">
<button type="submit">Upload</button>
</form>
</div>
and you should check this lines into app file
#livewireStyles
#livewireScripts
change route method to Post
Route::post('/upload', UploadFoto::class)->name('upload.foto.user');
I need to get a value of input to use below, how to do that?
I tried to like this but error says
Undefined variable: name
<div class="col-md-10 col-md-offset-1">
<input id="name" type="text" name="name" />
</div>
<div class="col-md-10 col-md-offset-1">
#php
$nameValue=$_GET['name'];
#endphp
<input id="name2" type="text" name="name2" value="{{$nameValue}}" />
</div>
$nameValue=Request::input('name')
From the blade template you can access the request parameters with the Request facade, you can also print it directly:
{{Request::input('name')}}
In latest versions you can also use:
{{request()->input('name')}}
You have to be aware that your input-values (here "name") ist only available after submitting the form.
If you want to access the form-values before submitting you should take a look at VueJS or any other frontend-framework (React, Angular). Or simply use jQuery.
Therefor you have to use JavaScript if you want to use the input-value before submitting.
Like the others said in the comments, you can access your form-values within your controller and then pass it to your view.
For example (from the documentation):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function formSubmit(Request $request)
{
$name = $request->input('name');
return view('form', ['name' => $name])
}
}
Now you can use the value within your view:
<input id="name2" type="text" name="name2" value="{{$name}}">
Another possibility would be to "by-pass" your controller and return your view directly from your routes.php:
Route::get('/form-submit', function(){
return view('form');
});
But I'm not sure if this is working and you could access $_GET/$_PSOT directly without using Laravels Request.
You can get inputs array from Request class:
Request::all()['your_input']
Also you can check if that input you want is exists not:
#isset(Request::all()['your_input'])
{{-- your input existed --}}
#else
{{-- your input does not existed --}}
#endisset
I am using the Laravel framework and the blade templating engine for one of my projects, where I have a route which looks like
Route::get('/problems/{problem-id}/edit', 'AdminController#editProblem');
I have editProblem method in AdminController which returns a view
public function editProblem(Problem $problem) {
return view('admin.problem-edit', compact('problem'));
}
and I have a button on a view which looks like
<button class="btn btn-xs btn-info pull-right">Edit</button>
Now I want to call this route with the $problem->id when the button will be clicked. I need to pass these value on the route.
how can I do that?
In my opnion, you should use url() Laravel method
To call you route with the problem's id you can do:
Edit
I used an anchor tag, but it will be rendered like you button tag because I kept the same style class you have defined.
Why you should use url() method ?
The reason is simple, the url method will get the full url to your controller. If you don't use this, href link will get appended with current url.
For example, supose you button is located inside a given page
yourdomain.com/a-given-page/
when someone click in your button, the result will be:
yourdomain.com/a-given-page/problems/{problem-id}/edit
when you would like to get this:
yourdomain.com/problems/{problem-id}/edit
Some considerations about your editProblem method
Your route has the '$id', so you need to receive this '$id' in your method
public function editProblem($problem_id) {
$problem = \App\Problem::find($problem_id); //If you have your model 'Problem' located in your App folder
return view('admin.problem-edit', compact('problem'));
}
Try This:
<button type="button" onclick="window.location='{{ url("users/index") }}'">Button</button>
Little Suggestion:
When you're defining routes in laravel give it a unique name, it helps you to keep track on each url like this
Route::get('/problems/{problem-id}/edit', 'AdminController#editProblem')->name('showProblemEditPage');
Route::post('/problems/{problem-id}/edit', 'AdminController#updateProblem')->name('updateProblem');
Now you use this route in blade with just name for post and get both
Exmaple of GET route :
<button type="button" onclick="window.location='{{ route("showProblemEditPage",[$problemIdParameter]) }}'">Button</button>
OR
<a href="{{ route("showProblemEditPage",[$problemIdParameter]) }}">Button</button>
OR
<button type="button redirectToUrl" data-redirect-url="{{ route("showProblemEditPage",[$problemIdParameter]) }}">Button</button>
<script>
$(document).on('click','.redirectToUrl',function(){
let getRedirectUrl = $(this).attr('data-redirect-url');
window.location.href= getRedirectUrl;
});
</script>
Example of POST route :
In case if you are submiting form via submit button click
<form action={{ route('updateProblem',[$problemIdParameter]) }}>
.....
<button type="submit">Submit</button>
</form>
In case if you are submiting form via ajax on button click
<form action={{ route('updateProblem',[$problemIdParameter]) }}>
.....
<button type="button" class="submitForm" >Submit</button>
</form>
<script>
$(document).on('click','.submitForm',function(){
let getForm = $(this).parents('form');
let getFormActionUrl = getForm.attr('action');
$.ajax({
url: getFormActionUrl,
.....
.....
.....
.....
.....
});
});
</script>
You will need to create a link to this route:
Edit
If you use named routes, this will be even easier:
Route::get('/problems/{problem-id}/edit', ['as' => 'problems.edit', 'uses' => 'AdminController#editProblem']);
And then you just need to call the route method:
Edit
Was asked for route inquiry.
so that :
<button onclick="window.location='{{ route("some_route_name") }}'"...>
</button>
in web.php
Route::get('/some_route_url', [SomeRouteController::class,'some_func'])->name('some_route_name');
I used the following code and it worked.
<button class="btn border button" id="go-back-btn" onclick="window.location='{!! route('getDashboardScreen') !!}?MilkCompanyID={!!session('MilkCompanyID')!!}'">Go back</button>