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
Related
i'm having trouble to get data from an input.
I try to be more specific
My application has many views, and each of these has an #include component that works as a search field.
For example the user types in the input the ID of the store, the controller compares the ID that user inserted with the DB store's ID and then compacts data and fill the views with infos of that specific store.
Im just testing how to get that data from the input but i'm getting this error:
Route [search.get_kcli] not defined.
Actually i'm trying to use that function only for get data by using a controller only for that input field.
What's wrong in it?
Thanks for help!
My code looks like this:
inside of app.blade.php
#auth
#include('partials.search')
#endauth
inside search.blade.php
<form method="POST" class="form-inline position-relative"
action="{{ route('search.get_kcli') }}">
#csrf
#method('POST')
<input class="form-control shadow-none" name="kcli" id="kcli" type="number"
placeholder="Codice..." aria-label="Search">
<button type="submit" class="btn btn-light search-btn"><i class="fas fa-search"></i></button>
</form>
Inside the SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class SearchController extends Controller
{
function get_kcli(Request $request) {
$kcli = $request->input('kcli');
dd($kcli);
}
}
Inside web.php
Route::post('/search', [App\Http\Controllers\SearchController::class, 'get_kcli'])->name('search');
Change
<form method="POST" class="form-inline position-relative"
action="{{ route('search.get_kcli') }}">
to
<form method="POST" class="form-inline position-relative"
action="{{ route('search') }}">
I'm very confused, I need your help, this is the error:
Missing required parameter for [Route: single.temp] [URI: singlepost/{name}] [Missing parameter: name]. (View: C:\Users\Toshiba\Desktop\working\mouhawla\resources\views\index.blade.php)
The search field:
<div class="search">
<form role="form" action="{{route('single.temp')}}">
<i class="fa fa-search"></i>
<div class="field-toggle">
<input type="text" name="name" class="search-form" autocomplete="off" placeholder="Search">
</div>
</form>
</div>
The method:
public function getPostByName($name) {
$products = DB::table('templates')
->where('name', $name)
->first();
return view('singlepost', compact('products'));
}
The route:
Route::get('/singlepost/{name}', 'App\http\controllers\TemplatesController#getPostByName')->name('single.temp');
The final view:
<h1 style="text-align: center;">ACH-template</h1>
<table>
<tr>
<td><img src="/storage/{{$products->image_path}}"></td>
<td><img src="/storage/{{$products->image_path2}}"></td>
<td><img src="/storage/{{$products->image_path3}}"></td>
<td>
<p>
<h2 style="text-align:center;">{{$products->name}}</h2>
</br>
<p>{{$products->description}}</p>
</p>
</td>
</tr>
</table>
<a href="/storage/{{$products->file_path}}" class="btn btn-primary">
<button class="btn" style="width:100%">
<i class="fa fa-download"></i> Download
</button>
</a>
The error is very explanatory. You are trying to use /singlepost/{name} route, but on your blade file, you are doing route('single.temp'), it is telling you that it needs the parameter name, else it cannot create the URL as it is a missing parameter.
You should have something like:
<form role="form" action="{{route('single.temp', ['name' => VALUE'])}}">
But that will not solve your problem, as you are trying to do a search, so you want something like /singlepost/John, and John is going to be input by the user on the input field. So you have to do an AJAX call because {{ route('single.temp') }} is going to be rendered by PHP and served to the user, so it is always going to miss the needed parameter.
What you can also do is get that value from the Request instead of a URL parameter.
You have defined a route which requires a parameter: {$name}. You have also used the route helper to generate a URL which takes the name of a route as the first argument and an array of parameters as an optional second argument.
When you have used route('single.temp') in your form action, you have not specified any parameters and so Laravel is throwing the error you're seeing. To resolve this error, you would need to specify a $name parameter as the second argument (i.e. route('single.temp', ['name' => 'something'])). This is not ideal though as if you're using $name as a search term, you don't know the value when the page is first rendered and so can't provide that value.
There are a few ways you could achieve your goal of searching records, a basic example of how you could do this follows.
web.php
Define two routes, the first to return a view with a form and another to process the form submission and show the results.
Route::get('/templates', [TemplateController::class, 'index'])
->name('templates.index');
Route::get('/templates/search', [TemplateController::class, 'search')
->name('templates.search');
TemplateController.php
Define the two functions which will be used when one of the routes defined above is requested.
class TemplateController extends Controller
{
// return a view
public function index()
{
return view('templates.search', ['templates' => []]);
}
// process the form submission
// perform a search for the $request search term
// return a view with the results
public function search(Request $request)
{
$request->validate([
'term' => ['required', 'string']
]);
$templates = Template::where('name', $request->term)->get();
return view('templates.search', ['templates' => $templates]);
}
}
templates/search.blade.php
{{-- create a form which will submit to the search route --}}
{{-- note I use GET rather than POST here, explained later --}}
<form action="{{ route('templates.search') }}" method="GET">
#csrf
<input type="text" id="term" name="term" />
<button type="submit">
{{ __('Search') }}
</button>
{{-- loop over and show results if there are any --}}
#forelse ($templates as $template)
{{ $template->name }}
#empty
{{ __('Empty') }}
#endforelse
</form>
The above should be self explanatory. My reason for using GET rather than POST in the search is because the value will be added to the URL as a query string parameter meaning it can be bookmarked or shared with ease.
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
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.
I am trying to delete data from my table employes by getting the id of the data and transferring it by using get route but i get the following error
ModelNotFoundException in Builder.php line 125: No query results for
model [App\employe].
her is my route
Route::get('/delete/{employe}', 'EmployeController#delete');
Route::post('/delete', 'EmployeController#handleDelete');
and i have model called employe to access my table
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class employe extends Model {
protected $fillable = array('fname','lname','age','sex','phone','email','houseno','city','kebele','state','username','password','workposition','salary','bankaccount','bankname','contactid','employedate');
}
part of my controller for deleting
public function delete(employe $employe)
{
// Show delete confirmation page.
return View('deleteemploye', compact('employe'));
}
public function handleDelete()
{
$employe = employe::findOrFail(Input::get('employe'));
$employe->delete();
return Redirect::action('EmployeController#index');
}
her is my view for deleting file
#extends('app')
#section('content')
<div class="page-header">
<h2>Delete {{$employe->fname}} Are you sure?</h2>
</div>
<form action="{{ action('EmployeController#handleDelete') }}" method="post" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="employe" id="employe" value="{{ $employe->id }}" />
<input type="submit" class="btn btn-default" value="Yes" />
No
</form>
#stop
Looks like laravel cant find the model with the primary key you are passing. Check the database and see if its there. If it is check the deleted_at field. If it has a date in it, it means it is already deleted. You can still find it by using withTrashed()
$employe = employe::withTrashed()->findOrFail(Input::get('employe'));
and if you have soft deleting enabled for this model, you can completely remove the given row by running
$employe = employe::withTrashed()->findOrFail(Input::get('employe'))->forceDelete();