How to pass a parameter in routes to the controller? - laravel

I am trying to refactor my code. If I could pass an argument in the routes page to the controller where the function is, then I could refactor many of function that are almost identical.
Something like this in Router:
Route::get('/entrepreneurs', 'HomeController#show')->withParameter('enterpreneur');
Which gives me something like this in Controller:
public function entrepreneurs($withParameter){
$entrepreneurs = DB::table('stars')->where('type', '=', $withParameter)->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
Is this possible?
-------- Update --------
Some of you are suggestion that I use Route Parameters:
Route::get('/entrepreneurs/{paramName}', 'HomeController#show');
However, I already use Route Model Binding to access individual pages (e.g. www.mywebsite.com/entrepreneurs/Mark_Zuckerberg)
So this is a conflicting with the solutions you guys provided!

Routes:
Route::get('/entrepreneurs/{enterpreneur}', 'HomeController#show');
HomeController.php:
public function show($enterpreneur = "")
{
$entrepreneurs = DB::table('stars')->where('type', '=', $enterpreneur)->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
To pass a static variable along with route
Route::get('/entrepreneurs', 'HomeController#show')->defaults('enterpreneur', 'value');
and access them in your controller as
public function show(Request $request)
{
$entrepreneur = $request->route('entrepreneur');
$entrepreneurs = DB::table('stars')->where('type', '=', $enterpreneur)->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
https://laravel.com/docs/5.4/routing#route-parameters

You can also do:
// --------------- routes ---------------------
Route::get("page", [
"uses" => 'HomeController#show',
"entrepreneurs" => "value"
]);
// -------------- controller -------------------
public function show(Request $request)
{
$entrepreneurs = DB::table('stars')->where('type', '=', $request->route()->getAction()["entrepreneurs"])->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}

I think you can try this:
Route::get('/entrepreneurs/{enterpreneur}', 'HomeController#show');
public function entrepreneurs($enterpreneur){
$entrepreneurs = DB::table('stars')->where('type', '=', $enterpreneur)->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
Hope this help for you !!!

If you want to pass param in your routes
Route::get('/entrepreneurs/type/{paramName}', 'HomeController#show');
And for an optionnal param :
Route::get('/entrepreneurs/type/{paramName?}', 'HomeController#show');
With optionnal paramater it should look like this in your controller :
public function show($paramName = null){
$entrepreneurs = DB::table('stars')->where('type', '=', $paramName)->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
You can have more information here : https://laravel.com/docs/5.4/routing#route-parameters

Related

laravel 8 passing data to redirect url

i have store function for save data to database and i want redirect to another url with passing $invoice variable
this is my store function :
$order = Order::create([
'no' => $invoice,
'spg' => $request->spg,
'nama' => $request->nama,
'hp' => $request->hp,
'alamat' => $request->alamat,
]);
return redirect('invoicelink', compact('invoice'));
this is my route file:
Route::resource('/', OrderController::class);
Route::get('invoicelink/{invoice}', [OrderController::class, 'invoicelink'])->name('invoicelink');
and this is my invoicelink function:
public function invoicelink($invoice)
{
dd($invoice);
}
How to do it? very grateful if someone help to solve my problem. thanks
If you look at the helper function you are calling, I don't think it is what you are looking for.
function redirect($to = null, $status = 302, $headers = [], $secure = null)
{
if (is_null($to)) {
return app('redirect');
}
return app('redirect')->to($to, $status, $headers, $secure);
}
I think what you want is
Redirect::route('invoiceLink', $invoice);
You can also use the redirect function, but it would look like this
redirect()->route('invoiceLink', $invoice);
You can see this documented here https://laravel.com/docs/8.x/responses#redirecting-named-routes
i found the solution:
web.php
Route::get('invoicelink/{invoice}', [OrderController::class, 'invoicelink'])->name('invoicelink');
controller:
public function invoicelink($invoice)
{
//dd($invoice);
return $invoice;
}
then use redirect:
return redirect()->route('invoicelink', [$invoice]);

Laravel model function best prickets

im new in Laravel , I have an issue as below
I make in category model query to check is category is exist or not
as below
public function scopeIsExist($query ,$id)
{
return $query->where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC')->first();
}
and my controller is
public function edit($id)
{
$dataView['category'] = Category::IsExist($id);
if(!$dataView['category'])
{
return view('layouts.error');
}else{
$dataView['title'] = 'name';
$dataView['allCategories'] = Category::Allcategories()->get();
return view('dashboard.category.edit')->with($dataView);
}
}
my problem is when I use method isEXIST if id not found it not redirect to error page but ween i remove ISEXIST AND replace it as below
$dataView['category'] = Category::where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC')->first();
it work well .
can any one help me
That's because local scope should return an instance of \Illuminate\Database\Eloquent\Builder. You should remove the first() in the scope and put it in the controller.
Redefine your scope like so:
public function scopeIsExist($query ,$id)
{
return $query->where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC');
}
In your controller edit method:
$dataView['category'] = Category::IsExist($id)->first();
You can have a look to the doc for local scopes https://laravel.com/docs/8.x/eloquent#local-scopes

Laravel how to pass request from controller to resource collection?

I will pass a parameter in the request. The query won't change. How can I pass the request to SurveyResouce
public function getAllSurveys(\Illuminate\Http\Request $request) {
$surveys = DB::table('surveys')
->select('id', 'survey_name')
->get();
return response()->json([
'error' => false,
'data' => SurveyResource::collection($surveys)
],
}
I want get the request parameters in the resource
public function toArray($request) {
$controller = new SurveyController(new SurveyRepository());
return [
'question' => $request->has('ques') ? $request->input('ques'):'',
];
}
You can try by directly using request() helper function. Like request('parameter');

Laravel / OctoberCMS frontend filter

I am using OctoberCMS and I have created a custom component. I am trying to create a frontend filter to filter Packages by the Tour they are assigned to.
This is what I have so far. The issue is that the code is looking for a tour field within the packages table rather than using the tour relationship. Does anyone have any ideas?
<?php namespace Jakefeeley\Sghsportingevents\Components;
use Cms\Classes\ComponentBase;
use JakeFeeley\SghSportingEvents\Models\Package;
use Illuminate\Support\Facades\Input;
class FilterPackages extends ComponentBase
{
public function componentDetails()
{
return [
'name' => 'Filter Packages',
'description' => 'Displays filters for packages'
];
}
public function onRun() {
$this->packages = $this->filterPackages();
}
protected function filterPackages() {
$tour = Input::get('tour');
$query = Package::all();
if($tour){
$query = Package::where('tour', '=', $tour)->get();
}
return $query;
}
public $packages;
}
I really appreciate any help you can provide.
Try to query the relationship when the filter input is provided.
This is one way to do it;
public $packages;
protected $tourCode;
public function init()
{
$this->tourCode = trim(post('tour', '')); // or input()
$this->packages = $this->loadPackages();
}
private function loadPackages()
{
$query = PackagesModel::query();
// Run your query only when the input 'tour' is present.
// This assumes the 'tours' db table has a column named 'code'
$query->when(!empty($this->tourCode), function ($q){
return $q->whereHas('tour', function ($qq) {
$qq->whereCode($this->tourCode);
});
});
return $query->get();
}
If you need to support pagination, sorting and any additional filters you can just add their properties like above. e.g;
protected $sortOrder;
public function defineProperties(): array
{
return [
'sortOrder' => [
'title' => 'Sort by',
'type' => 'dropdown',
'default' => 'id asc',
'options' => [...], // allowed sorting options
],
];
}
public function init()
{
$filters = (array) post();
$this->tourCode = isset($filters['tour']) ? trim($filters['tour']) : '';
$this->sortOrder = isset($filters['sortOrder']) ? $filters['sortOrder'] : $this->property('sortOrder');
$this->packages = $this->loadPackages();
}
If you have a more complex situation like ajax filter forms or dynamic partials then you can organize it in a way to load the records on demand vs on every request.e.g;
public function onRun()
{
$this->packages = $this->loadPackages();
}
public function onFilter()
{
if (request()->ajax()) {
try {
return [
"#target-container" => $this->renderPartial("#packages",
[
'packages' => $this->loadPackages()
]
),
];
} catch (Exception $ex) {
throw $ex;
}
}
return false;
}
// call component-name::onFilter from your partials..
You are looking for the whereHas method. You can find about here in the docs. I am not sure what your input is getting. This will also return a collection and not singular record. Use ->first() instead of ->get() if you are only expecting one result.
$package = Package::whereHas('tour', function ($query) {
$query->where('id', $tour);
})->get();

How To Create Conditional for Unique Validation (UPDATE/PATCH) on Form Request

I'm trying to get my controller cleaner by moving 'validation request' into a form request called 'BookRequest'.
The problem is on the update process, I try to create a condition to check, if it PATCH or POST with the following codes
MyRequest.php
public function rules()
{
// Check Create or Update
if ($this->method() == 'PATCH')
{
$a_rules = 'required|string|size:6|unique:books,column2,' .$this->get('id');
$b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->get('id');
}
else
{
$a_rules = 'required|string|size:6|unique:books,column2';
$b_rules = 'sometimes|string|size:10|unique:books,column3';
}
return [
'column1' => 'required|string|max:100',
'column2' => $a_rules,
'column3' => $b_rules,
'column4' => 'required|date',
'column5' => 'required|in:foo,bar',
'column6' => 'required',
'column7' => 'required',
'column8' => 'required',
];
}
.$this->get('id') it failed, the form still treat the unique on the update.
Controller#update
public function update($id, BookRequest $request)
{
$book = Book::findOrFail($id);
$input = $request->all();
$book->update($request->all());
return view('dashboards.book');
}
Controller#edit
public function edit($id)
{
$book = Book::findOrFail($id);
return view('dashboards.edit', compact('book'));
}
Controller#create
public function create()
{
return view('dashboards.create');
}
Controller#store
public function store(BookRequest $request)
{
$input = $request->all();
$book = Book::create($input);
return redirect('dashboards/book/index');
}
I try the alternative .$book->id, and it throw me an ErrorException Undefined variable: book
Any suggestion? I'm using Laravel 5.2 by the way
You are using book as your route parameter but trying to get with id. try this-
if ($this->method() == 'PATCH')
{
$a_rules = 'required|string|size:6|unique:books,column2,' .$this->route()->parameter('book');
$b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->route()->parameter('book');
}
Hope it helps :)

Resources