Laravel 5.6 - request() with 2 variables - laravel-5

I am filtering results via request()->variable. When there is only one variable the view comes back as it should eg.../products/summer, displaying only products that belong to a certain season.
What i'm trying to do is call in a second variable /products/summer?product_category=shirts displaying the season products as above while filtering those that belong to a specific category (eg.shirts).
This is my controller part:
public function index()
{
if (request()->season) {
$products = Product::with('seasons')->whereHas('seasons', function ($query){
$query->where('slug', request()->season);
})->get();
$product_categories = ProductCategory::with('seasons')->whereHas('seasons', function ($query){
$query->where('slug', request()->season);
})->get();
$season = Season::where('slug', request()->season)->firstOrFail();
} **elseif (request()->product_category)** {
$products = Product::with('product_categories')->whereHas('product_categories', function ($query){
$query->where('slug', request()->product_category);
})->get();
$product_categories = ProductCategory::with('seasons')->get();
$season = Season::where('slug', request()->season)->first();
}......
return view('season')->with([
'products' => $products,
'product_categories' => $product_categories,
'season' => $season,
]);
Is there a way to include season and product_category in the elseif above so that it corresponds to summer?product_category=shirts ?
My nav link passes this:
href="{{ route ('season.index',['season' => $season->slug, 'product_category' => $product_category->slug])}}"
The route is:
Route::get('/products/{season?}', 'SeasonController#index')->name('season.index');
Thank you for your time.

I did not understand exactly what you need
If this code was not useful,plese explan more and i change it:
my view :
<a
href="{{ route ('season.index',['season' =>$season->slug, 'product_category' => $product_category->slug])}}"
>send</a>
my route :
Route::get('/products', 'SeasonController#index')->name('season.index');
SeasonController controler :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SeasonController extends Controller
{
public function index(Request $request)
{
if ($request->get('season'))
{
# do something
}elseif($request->get('product_category'))
{
# do something
}
else
{
# do something
}
}
}

Related

Method Illuminate\Database\Eloquent\Collection::attach does not exist error in laravel 8

I was trying to add categories to products. I want to do it with a couple table between items and categories. I made a function in my controller to send it to the database. However, when I want to send it, I get the following error, and I don't know I can fix it. Method Illuminate\Database\Eloquent\Collection::attach does not exist.
Controller:
public function store(ItemsValidatorRequest $request)
{
if ($files = $request->image) {
$destinationPath = 'images';
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
}
else {
return redirect()->back()->with('warning', 'Mislukt');
}
$user = Auth::user()->id;
Item::create([
'user_id' => $user,
'item_title' => $request->titel,
'item_img' => $profileImage,
'item_description' => $request->beschrijving,
'item_price' => $request->prijs,
'item_slug' => $this->slugify($request->titel)
]);
$items = Item::latest()->get();
// line where it goes wrong
$items->each->categories()->attach($request->categories);
return redirect()
->route('admin.items.index')
->with('success', 'Het item is toegevoegd aan je verlanglijst');
}
My model :
public function categories()
{
return $this->belongsToMany('App\Models\Category');
}
Laravels higher order function calls, take a single method call, not multiple. Therefor if you create an helper method on the Item class, it will solve your problem.
class Item {
public function attachCategories($categories) {
$this->categories()->attach($categories);
}
}
Which will make it possible to assign categories like so.
$items->each->attachCategories($request->categories);

Laravel Closure Request

Assalamualaikum guys, i have some problems with my code. i tried to make search by using request parameters on laravel. and here is my code views.
$maintenance->with([
'user_post' => function($query, Request $request){
if($request->has('searchBy') && $request->has('searchQuery'))
{
$parse_query = explode('.',$request->query('searchBy'));
$is_user = $parse_query[0] == 'user_post'? true : false;
if($is_user)
{
$query->where($parse_query[1],'LIKE','%'.$request->query('searchQuery').'%');
}
}
},
'dt_project'
]);
when i tried to execute on browser, it return
1/1) ErrorException
Undefined variable: request
what should i do? thanks to the moon and back. hehehe
try this, change your line 2 to:
'user_post' => function($query) use($request){
explanation:
Request $request can only be used in controller functions like:
public function store(Request $request)
{
//code here
}
in order to pass the $request parameter inside another function, use use (this is also known as variable inheriting):
public function store(Request $request)
{
$user= User::with(['roles' => function($query) use($request){
^^^
$query->where('roles.id', $request['role_id'])->first();
}])->get();
}

How to pass a parameter in routes to the controller?

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

Search Method with pagination result

I made a search method (GET) with some filters, the only problem that i have is when i run the search result i get the results with pagination with the adresse like :
search?q=&type_licence_id=&activite_licence_id=&structure_id=8
when i click on page 2 for exemple i have :
search?page=2
So it's display me anymore the results from the search query.
Maybe i done something wrong on my controller ? Hope someone could help me , thanks a lot in advance
here my controller :
public function search(Request $request)
{
$structure = Structure::select('num_structure', 'nom_structure' , 'id')
->get()
->mapWithKeys(function($i) {
return [$i->id => $i->num_structure.' - '.$i->nom_structure];
});
$activite = ActiviteLicencie::pluck('lb_activite' , 'id');
$type_licence = Type_licence::pluck('lb_type' , 'id');
$query = Licencies::query();
$filters = [
'type_licence_id' => 'type_licence_id',
'activite_licence_id' => 'activite_licencie_id',
'structure_id' => 'structure_id',
];
foreach ($filters as $key => $column) {
$query->when($request->{$key}, function ($query, $value) use ($column) {
$query->where($column, $value);
});
}
$licencies = $query->paginate(10);
return view('licencie/recherche', compact('licencies' , 'structure' , 'activite' , 'type_licence'));
}
I use the following in my blade template:
{{ $licencies->appends(Request::all())->links() }}
It appends all your request parameters to the pagination.
Check 'Appending To Pagination Links' on https://laravel.com/docs/5.4/pagination#displaying-pagination-results for information
You could customize the Pagination URL by
$licencies = $query->paginate(10);
$licencies->setPath($request->fullUrlWithQuery());
Docs:
https://laravel.com/docs/5.4/pagination#displaying-pagination-results
https://laravel.com/api/5.4/Illuminate/Pagination/LengthAwarePaginator.html#method_setPath

Laravel Model to View - Undefined variable

I'm sure I'm missing something blindingly obvious but cannot see to get the division name to appear on my view.
It keeps returning Undefined variable: division_name
DIVISON.PHP (Model)
<?php
class Division extends \Eloquent {
protected $table = 'divisions';
public function scopeGetDivisionName($query, $slug)
{
return $query->select('division_name')
->join('division_industry_job', 'division_industry_job.division_id', '=', 'divisions.id')
->join('industryjobs', 'division_industry_job.industry_job_id', '=', 'industryjobs.id')
->where('industryjobs.slug', '=', $slug);
}
}
JOBCONTROLLER.PHP (Controller)
public function showdivisionjob($slug)
{
$job = IndustryJob::where("slug", "=", $slug)->first();
$division_name = Division::getDivisionName($slug)->firstOrFail();
return View::make('job')->with('job', $job, $division_name);
}
JOB.BLADE.PHP (View)
{{$division_name->division_name}}
{{$job->job_title}}
You're not passing the variable to your view properly.
// This won't work
return View::make('job')->with('job', $job, $division_name);
It should be
return View::make('job')->with('job', $job)
->with('division_name', $division_name);
Or
return View::make('job', array(
'job' => $job,
'division_name' => $division_name
));
You can use also the compact method for passing variables to your view :
public function showdivisionjob($slug)
{
$job = IndustryJob::where("slug", "=", $slug)->first();
$division_name = Division::getDivisionName($slug)->firstOrFail();
return View::make('job', compact('job', 'division_name'));
}

Resources