laravel send parameter in route - laravel

Is thier anyway to do somethins like this ,
in web.php
Route::get('/test', 'testController#test');
in test Controller
public function test ($url)
{
//while $url store test in route
}
I know only if I send parameter I have to use
Route::get('/{test}', 'testController#test');
UPDATE
I want to do something like this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
in my controller
public function test ($url)
{
while $url store test,test2in route
}
LASTEST UPDATE
I dont want to use {url}
I want to make /test = $url when I enter to url/test
In my web.php I use this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
The reason that I want to do something like this because I want to make 1 function that alll route can use In my controller I do this .
public function test($url,$preview=null)
{
//$url shoud be test or test 2
try {
$test = (isset($preview)) ? test::where('test.id',$url)->first()
} catch (\Exception $e) {
return redirect('notfound');
}
}
I dont want todo something like this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
and In controller
public function test($preview=null)
{
//$url shoud be test or test 2
try {
$test = (isset($preview)) ? test::where('test.id','test)->first()
} catch (\Exception $e) {
return redirect('notfound');
}
}

You need to combine both elements
Route::get('/test/{url}', 'testController#test');
want to make /test = $url
You can't, but you can have /test?foo=$url instead. So you keep your route like
Route::get('/test', 'testController#test');
Then add Request $request as controller method argument (and you remove $url)
public function test(Request $request) {
...
Finally you obtain your url with
$url = $request->input('foo');

Your Route
Route::post('/test', 'testController#test')->name('test);
If you use blade.
<a href="{{ route('test') }}"
onclick="event.preventDefault();
document.getElementById('test_id').submit();">
Test Click
</a>
{!! Form::open(['url' => route('test'), 'method' => 'post', 'id' => 'test_id']) !!}
<input type="hidden" name="url" value="{{ $url}}">
{!! Form::close() !!}
In your controller.
public function test(Request $request)
{
$data = $request->all();
$url = $data['url'];
//do something with your url...
}

Related

How to change locale in laravel route?

I am working on Laravel localization. I have all done but facing issue. When I change language from dropdown page successfully transalated but language in ROUTE not change.
In web.php I have setup this,
Route::get('/', function () {
return redirect(app()->getLocale());
});
Route::get('language/change', [LocalizationController::class, 'changeLanguage'])->name('changeLang');
Route::group(
[
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}'],
'middleware' => 'setlocale'
],function () {
Route::get('/', [MainController::class, 'index'])->name('main.index');
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::group(['middleware' => ['auth']], function () {
//
});
});
I have added below code in Middleware,
public function handle(Request $request, Closure $next)
{
if (session()->has('locale')) {
App::setLocale(session()->get('locale'));
}
return $next($request);
}
In view file I have added this code,
<select class="form-control languageSelector">
<option {{ session()->get('locale') == 'en' ? 'selected' : '' }} value="en">πŸ‡ΊπŸ‡Έ <span style="font-weight: bolder !important">En</span></option>
<option {{ session()->get('locale') == 'fr' ? 'selected' : '' }} value="fr">πŸ‡«πŸ‡· <span style="font-weight: bolder !important">Fr</span></option>
</select>
$(document).ready(function(){
var url = '{{ route('changeLang') }}';
$('.languageSelector').change(function(){
window.location.href = url + "?lang="+ $(this).val();
});
});
when I select language french from dropdown in route always see EN.
In Controller I have added,
public function changeLanguage(Request $request)
{
App::setLocale($request->lang);
session()->put('locale', $request->lang);
return redirect()->back();
}
How can I solve it?
Thanks Stack overflow. I have solve it by using this technique,
public function changeLanguage(Request $request)
{
App::setLocale($request->lang);
session()->put('locale', $request->lang);
$url = url()->previous();
$route = app('router')
->getRoutes($url)
->match(app('request')->create($url))
->getName();
return redirect()->route($route, ['locale' => $request->lang]);
}
The better way to use the session for this purpose because its a cheap way to define URL with language code, and here is the best way you can use on anywhere. you can follow all instruction
web.php
kernal.php
middleware
at the end you wrote this line of code in controller?
[1]: https://i.stack.imgur.com/p63eB.png

Laravel: Accessing Path Function in Model in Index File

I have set up the following function in my model:
public function path() {
return route('news.show', ['id' => $this->id, 'slug' => $this->slug]);
}
I would now like to access that function in my index.blade.php file -- like this:
#foreach ($articles as $article)
<a href="{{ $article->path() }}">
// rest of code goes here
</a>
#endforeach
But when I try this, I get the following error:
Facade\Ignition\Exceptions\ViewException
Missing required parameters for [Route: news.show] [URI: news/{id}/{slug}]. (View: C:\laragon\www\startup-reporter\resources\views\news\index.blade.php)
Here is what my routes (web.php) looks like:
Route::get('news', 'NewsController#index')->name('news.index');
Route::get('news/create', 'NewsController#create')->name('news.create');
Route::get('news/{id}/{slug}', 'NewsController#show')->name('news.show');
Route::get('news/{id}/edit', 'NewsController#edit')->name('news.edit');
Route::post('news', 'NewsController#store')->name('news.store');
Route::put('news/{id}', 'NewsController#update');
And here is my controller:
// Index
public function index() {
$news = News::latest()->get();
return view('news.index', ['articles' => $news]);
}
// Show
public function show(News $id) {
return view('news.show', compact('id'));
}
Any idea why this is not working and what I need to do to get this to work?
Thanks.
In your routes file you have defined 2 parameters, {id} and {slug}.
But in your controller you have only accepted 1 parameter, $id.
You should amend your show controller method like this:
// Show
public function show(News $id, $slug) {
return view('news.show', compact('id'));
}

Why does the old() method not work in Laravel Blade?

My environment is Laravel 6.0 with PHP 7.3. I want to show the old search value in the text field. However, the old() method is not working. After searching, the old value of the search disappeared. Why isn't the old value displayed? I researched that in most cases, you can use redirect()->withInput() but I don't want to use redirect(). I would prefer to use the view(). method
Controller
class ClientController extends Controller
{
public function index()
{
$clients = Client::orderBy('id', 'asc')->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
public function search()
{
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
$query = Client::query();
if (isset($clientID)) {
$query->where('id', $clientID);
}
if ($status != "default") {
$query->where('status', (int) $status);
}
if (isset($nameKana)) {
$query->where('nameKana', 'LIKE', '%'.$nameKana.'%');
}
if (isset($registerStartDate)) {
$query->whereDate('registerDate', '>=', $registerStartDate);
}
if (isset($registerEndDate)) {
$query->whereDate('registerDate', '<=', $registerEndDate);
}
$clients = $query->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
}
Routes
Route::get('/', 'ClientController#index')->name('client.index');
Route::get('/search', 'ClientController#search')->name('client.search');
You just need to pass the variables back to the view:
In Controller:
public function search(Request $request){
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
...
return view('auth.client.index', compact('clients', 'clientID', 'status', 'nameKana', 'registerStartDate', 'registerEndDate'));
}
Then, in your index, just do an isset() check on the variables:
In index.blade.php:
<input name="clientID" value="{{ isset($clientID) ? $clientID : '' }}"/>
<input name="status" value="{{ isset($status) ? $status : '' }}"/>
<input name="nameKana" value="{{ isset($nameKana) ? $nameKana : '' }}"/>
...
Since you're returning the same view in both functions, but only passing the variables on one of them, you need to use isset() to ensure the variables exist before trying to use them as the value() attribute on your inputs.
Also, make sure you have Request $request in your method, public function search(Request $request){ ... } (see above) so that $request->input() is accessible.
Change the way you load your view and pass in the array as argument.
// Example:
// Create a newarray with new and old data
$dataSet = array (
'clients' => $query->paginate(Client::PAGINATE_NUMBER),
// OLD DATA
'clientID' => $clientID,
'status' => $status,
'nameKana' => $nameKana,
'registerStartDate' => $registerStartDate,
'registerEndDate' => $registerEndDate
);
// sent dataset
return view('auth.client.index', $dataSet);
Then you can access them in your view as variables $registerStartDate but better to check if it exists first using the isset() method.
example <input type='text' value='#if(isset($registerStartDate)) {{registerStartDate}} #endif />

How to pass variable from blade to LARAVEL commands

I need to pass user_id from blade to routes, and then use the variable into a laravel command. How can I do?
lista_lavori.blade.php
<div class="box-tools">
<i class="fa fa-print"></i>
</div>
web.php - route
Route::get('/stampasingoloreport/{id}', function ($id) {
Artisan::call('StampaSingoloReport:stampasingoloreport');
return back();
});
StampaSingoloReport.php - Commands
public function handle()
{
// static id i need to change this dinamically
$id = 5;
$utente = \App\User::where('id',$id)->get();
//invio email per avvertire l'utente
$data = array('utenti'=>$utente);
Mail::send('mail.invioMailReportLavoriSingoli', $data, function($message) {
$message->to('rubertocarmine94#gmail.com', 'Admin Risorse Umane') ->subject('Email da piattaforma BancaStatoHR') ;
$message->from('rubertocarmine94#gmail.com') ;
});
}
You can pass an array to call() method like
Route::get('/stampasingoloreport/{id}', function ($id) {
Artisan::call('StampaSingoloReport:stampasingoloreport',[
'id' => $id
]);
return back();
});
Now in your handle method, you can access these arguments like
protected $signature = 'StampaSingoloReport:stampasingoloreport { id } ' ;
function handle(){
$this->argument('id');
// your code
}
Hope this helps

post method on two actions within same controller in laravel

Following is my route file i.e web.php
Route::post('finddomainname','DomainController#finddomainname')->name('finddomainname');
Route::post('registerdomains','DomainController#registerdomains')->name('registerdomains');
Following is the code on my DomainController for both the actions used,
public function finddomainname(Request $request)
{
$this->validate($request,
['searchdomaintxt'=>'required',
'searchdomainext'=>'required']);
$searchdomaintxt = $request->input('searchdomaintxt');
$searchdomainext = $request->input('searchdomainext');
$domainname="";
if($searchdomaintxt && $searchdomainext)
{
foreach($searchdomainext as $ext)
{
$domainname.=$searchdomaintxt.".".$ext.",";
}
//dd($domainnames);
$domainnames= rtrim($domainname,',');
$response=$this->soap->multidomainsearch($domainnames);
$result=$response['RESPONSE']['DOMAINSEARCH'];
//dd($result);
if($result){
//return redirect()->action('searchresults', array('response' => $result));
return view('domain.searchresults',['response'=>$result]);
}
else
{
return view('domain.searchresults',['response'=>'']);
}
}
}
Following is the second action on which control come after submitting data
public function registerdomains(registerDomainsValidation $request)
{
$domains=$request->input('selecteddomains');
$selectedyear =$request->input('selectedyear');
$domaincontactid=\Session::get('domaincontactid');
$alldomains='';
foreach($domains as $domain)
{
$alldomains.=$domain.",";
}
$alldomains=rtrim($alldomains,',');
$response=$this->soap->registerdomains($alldomains,$domaincontactid,$selectedyear);
return view('domain.searchresults',['response'=>$response]);
}
but when i submit data it will show me this error
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
You are trying to access your POST route using a GET request, that's why you are receiving a MethodNotAllowedHttpException. To solve this issue, make sure that your <form></form> tag contains the appropriate method attribute.
<form action="{{ YOUR_URL }}" method="POST">
...
</form>
Or if you want to perform the request inside your controller, you can use Guzzle to send http requests. In your controller you can do:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('POST', 'YOUR_URL', [
'form_params' => [
'foo' => 'bar'
]
]);

Resources