How do I change the route depending on selection in laravel - laravel

I'm trying to create a page that lets the user select a product and then when they press "add to cart" that product then gets sent to the cart page.
On my product page I can have the same item that has 2 or more codes attached to it, so I've created a selection that has the codes and the user then has to pick one of them
and then press "add to cart" button to go to the cart page.
So the way I have it at the moment is that the form grabs the id of the product page and not of the selection box.
What I would like to know is how would I go about changing the route depending on what I've selected.
Here is my code
<form action="{{ route('product.addToCart', ['id' => $product->id]) }}" method="POST">
{{ csrf_field() }}
<div class="row">
<div class="col-lg-12 pl-0">
<select class="form-control mb-2" id="supplier_code" name="supplier_code">
#foreach($parent_product as $parent)
<option value="{{ $parent->supplier_code }}">{{ $parent->supplier_code }}</option>
#if(count($parent->parent))
#foreach($parent->parent as $child)
<option value="{{ $child->supplier_code }}">{{ $child->supplier_code }}</option>
#endforeach
#endif
#endforeach
</select>
</div>
</div>
{{ Form::submit('Add to Cart', array('class' => "btn btn-dark btn-lg btn-block")) }}
</form>
This is my function
public function getAddToCart(Request $request, $id)
{
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$contacts = Contact::all();
$product = Product::find($id);
$supplier_code = $request->supplier_code;
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id, $supplier_code);
$request->session()->put('cart', $cart);
return view('public.shopping-cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice, 'menus_child' => $menus_child, 'contacts' => $contacts, 'supplier_code' => $supplier_code]);
}
This is my product list page where the user will click on a product to get its details.
<div class="col-xl-9 col-lg-8 col-md-12 product-list">
<div id="parent">
<div class="row grid-container">
#foreach($products as $product)
<?php
$cat_slug = "";
?>
#foreach($product->category as $category)
<?php
$cat_slug .= " ".$category->slug
?>
#endforeach
<?php
$product_image = getImagesArray($product->image);
?>
<div class="product_items col-xl-2 col-lg-4 col-md-4 col-sm-4 {{ $cat_slug }}">
<a href="{!! route('product.item', [$product->slug]) !!}">
<div>
#if(!empty($product_image))
<img src={!! "product_images/products/$product_image[0]" !!}>
#endif
<p>
{!! $product->title !!}
</p>
</div>
</a>
</div>
#endforeach
</div>
</div>
</div>
I'm not sure if I need to add anything else, so if I do need to please let me know

Change this:
<a href="{!! route('product.item', [$product->slug]) !!}">
to this:
<a href="{{ route('product.item', $product->id) }}">

Related

Laravel Livewire Select Search Dropdown not working

I have a form in the Laravel Livewire project and try to search and select users from the database. When I search User then search results in users, but nothing to select. Also, no error showing just page refresh. my code is below:
I'm trying this
livewire component view
<div class="col-md-4">
<div class="form-group row">
<label class="control-label col-md-2 col-sm-2">Select User</label>
<div class="col-md-10 col-sm-10 ">
<div>
<select wire:model="user_id" class="form-control" name="user_id" required>
<option></option>
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->username}} : {{ $user->fullname }}</option>
#endforeach
</select>
</div>
<div style="position:relative">
<input wire:model.debounce.500ms="inputsearchuser" class="form-control relative" type="text"
placeholder="search..."/>
</div>
<div style="position:absolute; z-index:100">
#if(strlen($inputsearchuser)>2)
#if(count($searchusers)>0)
<ul class="list-group">
#foreach($searchusers as $searchuser)
<li class="list-group-item list-group-item-action">
<spanwire:click
="selectuser({{$searchuser->id}},{{$searchuser->terms}})">{{$searchuser->username}}
: {{$searchuser->fullname}}</span>
</li>
</ul>
#endforeach
#else
<li class="list-group-item">User Not Found...</li>
#endif
#endif
</div>
</div>
</div>
</div>
livewire component
class MyLiveWireComponent extends Component
{
public $j = 1;
public $users = [];
public $inputsearchuser = '';
public $user_id;
public function selectuser($user_id,$terms)
{
$this->user_id = $user_id;
$this->terms = $terms;
$this->inputsearchuser = '';
}
public function render()
{
$searchusers = [];
if (strlen($this->inputsearchuser) >= 2) {
$searchusers = User::Where('username', 'LIKE', '%' . $this->inputsearchuser . '%')
->get();
}
return view('livewire.admin.orders.add-order', ['searchusers' => $searchusers])->layout('components.layouts.admin');
}
}
Change this:
<spanwire:click="selectuser({{$searchuser->id}},{{$searchuser->terms}})">
{{$searchuser->username}} : {{$searchuser->fullname}}
</span>
To:
<span wire:click.prevent="selectuser({{$searchuser->id}},{{$searchuser->terms}})">
{{$searchuser->username}} : {{$searchuser->fullname}}
</span>
Your component should have a single-level root element only. Also, add wire:key in your element inside of the loop.
<ul class="list-group">
#foreach($searchusers as $key => $searchuser)
<li wire:key="{{'users'.$key}}" class="list-group-item list-group-item-action">
<span wire:click="selectuser({{$searchuser->id}},
{{$searchuser->terms}})">{{$searchuser->username}}
: {{$searchuser->fullname}}</span>
</li>
#endforeach
</ul>
Did you change it to wire:click.prevent as suggested above? Otherwise, it does not prevent the default action from occurring, and can cause that exact behavior.

Laravel search from multi select dropdown

I am trying to create a search filter using dropdown selections. The code only shows results when all dropdowns (make and model) are selected. But it should work even single dropdown (either make or model)is selected. At the moment, if I select a single dropdown, the result page shows "No Matching Data found". this is what I have done -
Controller
class CarFrontController extends Controller
{
public function index_classiccars(Request $request)
{
$filterMakes = DB::table('cars')->select('make')->distinct()->get()->pluck('make');
$filterModels = DB::table('cars')->select('model')->distinct()->get()->pluck('model');
$classiccar = Car::query();
if ($request->has('make')) {
$classiccar->where('make', $request->make);
}
if ($request->has('model')) {
$classiccar->where('model', $request->model);
}
return view(
'layouts.frontend.cars.classiccars_index',
[
'filterMakes' => $filterMakes, 'filterModels' => $filterModels,
'classiccars' => $classiccar->get()
]
);
}
public function store(Request $request)
{
return $request->all();
return view('layouts.frontend.cars.classiccars_index');
}
}
data blade
#forelse ($classiccars as $car)
<div class="row">
<div class="col-lg-5 col-md-5 col-pad">
<div class="car-thumbnail">
<a href="car-details.html" class="car-img">
<div class="price-box">
<span>£{{ $car->price }}</span>
</div>
#php $i=1; #endphp
#foreach ($car->join_caralbum as $image)
#if ($i>0)
<img class="d-block w-100" src="{{asset($image->image_location)}}" alt="car" height="225px" >
#endif
#php $i--; #endphp
#endforeach
</a>
<div class="carbox-overlap-wrapper">
<div class="overlap-box">
<div class="overlap-btns-area">
<a class="overlap-btn" href="{{ url('car_show/'.$car->id) }}">
<i class="fa fa-eye-slash"></i>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-7 col-md-7 col-pad align-self-center">
<div class="detail">
<h3 class="title">
{{ $car->make }}
</h3>
<ul class="custom-list">
<li>
{{ $car->model }} /
</li>
......
</ul>
<ul class="facilities-list clearfix">
.....
.....
....
</ul>
</div>
</div>
</div>
</div>
#empty
No matching data found
#endforelse
filter blade
{!! Form::open(['action'=>'CarFrontController#index_classiccars','method'=>'GET']) !!}
<select class="form-control" name="make" id="make">
<option> Make(All)</option>
#foreach ($filterMakes as $make)
<option value="{{ $make }}">{{ $make }}</option>
#endforeach
</select><br>
<select class="form-control" name="model" id="model">
<option> Model(All)</option>
#foreach ($filterModels as $model)
<option value="{{ $model }}">{{ $model }}</option>
#endforeach
</select><br>
{{ Form::submit('Update Search',['class'=>'btn btn-primary']) }}
Your query results empty because even if you don't select any of your options, you actually do. If options don't have a value, the value is the text you give it to the option.
In your case, if you select just a model, actually you are selected 'Make(All)' option too. You can see this simply by putting dd($request->all()) on your index_classiccars method.
For checking selects, you can give empty value to first(default) option and control it with request()->filled('input').

Pass data from form submit to controller via get Method

can anyone tell, what is wrong with the following way to pass the data from view->route->controller. Currently I get Missing required parameters for [Route: show.exclusion] [URI: exclusion/create/{id}]
This is my view part:
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">In welcher Gruppe möchten Sie User einladen?</div>
<div class="panel-body">
{!! Form::open(array('route'=>'show.exclusion', 'method'=>'get', 'id'=>'$group->idgroup')) !!}
<div class="form-group">
{{Form::label('choosegroup', 'Wähle eine Gruppe')}}
<select class="form-control m-bot15" name="idgroup">
#foreach($groups as $group)
<option id="{{ $group->idgroup }}">{{ $group->groupname }}</option>
#endforeach
</select>
<!--{{ csrf_field() }}-->
</div>
<div>
{{Form::submit('Search',['class' => 'btn btn-primary'])}}
<a class="btn btn-default btn-close" href="{{ route('home') }}">Cancel</a>
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
This is my route...
Route::get('exclusion/create/{id}', 'ExclusionController#show')->name('show.exclusion');
And here you can see my controller function...
public function show($id)
{
$groupid = $id;
$members = V_Exclusion::where([['idgroup', $groupid],['groupadmin', Auth::id()]])->get();
$groups = V_Exclusion::where('groupadmin', Auth::id())->get();
return view('exclusions.createexclusion')
->with('members', $members)
->with('groups', $groups);
}
Try this.
In Route
Route::get('exclusion/create/{id}', 'ExclusionController#show');
{!! Form::open(array('route'=>['exclusion/create',$group->idgroup], 'method'=>'get', 'id'=>'$group->idgroup')) !!}

Laravel chosen-select retrieving old value from the form

I am trying to retrieve old value from my form on the edit form, but it seems impossible to find an answer, because everyone in the world decided to use Form::select from laravelcollective/html library. I am trying to use the regular HTML to work this, and it's not able to retrieve old value from the form.
This is my HTML Code.
<div class="col-xs-12 form-group">
<label class="control-label">Role*</label>
<select name="roles[]" data-placeholder="Choose a Role for this User..." class="chosen-select" multiple tabindex="4">
<option value="">Select</option>
#foreach ($roles as $key => $value)
<option value="{{ $key }}" {{ in_array($key, old("roles")) ? "selected":"") }} >{{ $value }}</option>
#endforeach
</select>
</div>
This is my controller code.
public function edit($id)
{
$roles = Role::get()->pluck('name', 'id');
$user = User::findOrFail($id);
return view('admin.users.edit', compact('user', 'roles'));
}
I am trying to convert the following into regular html
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('role', trans('global.users.fields.role').'*', ['class' => 'control-label']) !!}
{!! Form::select('role[]', $roles, old('role') ? old('role') : $user->role->pluck('id')->toArray(), ['class' => 'form-control select2', 'multiple' => 'multiple', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('role'))
<p class="help-block">
{{ $errors->first('role') }}
</p>
#endif
</div>
</div>
Try this:
<div class="col-xs-12 form-group {{ $errors->has('role') ? 'has-error' : '' }}">
<label for="role" class="control-label">Role *</label>
<select class="form-control select2" name="role[]" id="role" required multiple>
#foreach ($roles as $id => $label)
<option value="{{ $id }}" #if (collect(old('role', $user->role->pluck('id') ?? []))->contains($id)) selected="selected" #endif>{{ $label }}</option>
#endforeach
</select>
<span class="help-block">
#if ($errors->has('role'))
{{ $errors->first('role') }}
#endif
</span>
</div>
In your controller's update/store function, make sure you either use the built-in validation methods, which will populate the session on any errors.
or
If you have other checks, make sure you return the input when redirecting back.
return redirect()->back()
->withInput() // <- return input with redirect, will populate session
->with('error', 'Persist failed'); // <- optional

Invalid argument supplied for foreach with laravel 5.4

I'm getting Invalid argument supplied for foreach() error in my view after publishing a post and the code i use for looping in my controller is this:
public function edit($id)
{
$post = Post::find($id);
$categories = Category::all();
$cats = array();
foreach ($categories as $category) {
$cats[$category->id] = $category->name;
}
$tags = Tag::all();
$tags2 = array();
foreach ($tags as $tag) {
$tags2[$tag->id] = $tag->name;
}
return view('admin.posts.edit')->withPost($post)->withCategories($cats)->withTags($tags2);
}
this is the only part i handle loops in my postcontroller edit section. And I know the issue is from Tags loop because when I remove the tags code in my view other part will show up correctly.
Oh and this is the loop i use in my view:
#extends('layouts.app')
#section('content')
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">{{ $post->title }}</div>
<div class="panel-body">
<p><img src="{{ asset('uploads/' . $post->image) }}" alt="{{ $post->title }}" class="img-responsive" /></p>
<p>{!! $post->body !!}</p>
</div>
<div class="tags">
#foreach ($tags as $tag)
<span class="label label-default">{{ $tag }}</span>
#endforeach
</div>
</div>
</div>
#endsection
#section('sidebar')
<div class="col-md-4">
<div class="panel panel-primary">
<div class="panel-heading"><i class="fa fa-info"></i> Post Info</div>
<div class="panel-body">
<dl class="dl-horizontal">
<label>URL:</label>
<p>{{ url('blog/'.$post->slug) }}</p>
</dl>
<dl class="dl-horizontal">
<label>Created On:</label>
<p>{{ date('M j, Y h:ia', strtotime($post->created_at)) }}</p>
</dl>
<dl class="dl-horizontal">
<label>Last Update:</label>
<p>{{ date('M j, Y h:ia', strtotime($post->updated_at)) }}</p>
</dl>
<dl class="dl-horizontal">
<label>Posted In:</label>
<p>{{ $post->category->name }}</p>
</dl>
<hr/>
<div class="row">
<div class="col-md-6">
{!! Html::linkRoute('posts.edit', 'Edit', array($post->id), array('class' => 'btn btn-warning btn-block')) !!}
</div>
<div class="col-md-6">
{!! Form::open(['route' =>['posts.destroy', $post->id], 'method' => 'DELETE']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger btn-block']) !!}
{!! Form::close() !!}
</div>
</div>
<hr/>
{!! Html::linkRoute('posts.index', '<< Back to Posts', [], array('class' => 'btn btn-primary btn-block')) !!}
</div>
</div>
</div>
#endsection
PS: I'm using Laravel 5.4
Post updated view!
You can't get tags via post so Try this...
<div class="tags">
#foreach ($tags as $tag)
<span class="label label-default">{{ $tag }}</span>
#endforeach
</div>
Try:
return view('admin.posts.edit')->with("post",$post)->with("categories",$cats)->with("tags",$tags2);
and at view
<div class="tags">
#foreach ($tags as $tag)
<span class="label label-default">{{ $tag->name }}</span>
#endforeach
</div>
in your table if your primary key name if not id you have to mention in your relationship Link
2.for your post has one category so you can show this into your view like this
{{ $post->category->name }}
if you get result you can use it. but seems you need tag key and value pair so use this methods
$tags = Tag::where('post_id',$post->id)->groupBy('id')->get();
or try your way
$tags = Tag::all();
$tags2 = array();
foreach ($tags as $tag) {
$tags2[$tag->id] = $tag->name;
}
return view('admin.posts.edit',compact($post,$tags2,$cats));
in your view try this
#foreach ($tags as $key => $tag)
<span class="label label-default">{{ $tag }}</span>
#endforeach

Resources