I'm learning Laravel 5.2 for first time, and I need to repopulate a form when the validation fails.
I was able to do so with single inputs as 'name' or 'description', but I couln't find out how to do it with the 'category' which is a multiple select.
View:
<form action="{{ url('addproduct') }}" method="POST">
{!! csrf_field() !!}
<div class="form-group">
<label for="#productName">Name:</label>
<input id="productName" class="form-control" name="name" type="text" placeholder="Product name" value="{{ old('name') }}">
</div>
<div class="form-group">
<label for="#productDescription">Description:</label>
<textarea id="productDescription" class="form-control" name="description" rows="3" placeholder="Product description" value="{{ old('description') }}"></textarea>
</div>
#if ($categories)
<div class="form-group">
<label for="#productCategory">Category:</label>
<select id="productCategory" class="form-control" name="category[]" multiple>
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
#endif
<div class="form-group">
<label for="#productQuantity">Quantity:</label>
<input id="productQuantity" class="form-control" name="quantity" type="number" min="0" value="0">
</div>
<button class="form-control btn btn-success" type="submit">Add Product</button>
</form>
Controller:
public function add(Request $request) {
$data = array();
$data['msgAdded'] = false;
$data['categories'] = Category::select('name', 'id')->get();
if ($request->isMethod('post')) {
$this->validate($request, [
'name' => 'required|max:50',
'description' => 'required|max:200',
'category' => 'required',
'quantity' => 'required|min:0',
]);
$product = new Product;
$product->name = $request->name;
$product->description = $request->description;
$product->quantity = $request->quantity;
$product->save();
foreach ($request->category as $cat) {
$category = Category::find($cat);
$category->products()->attach($product->id);
}
$data['msgAdded'] = true;
}
$data['view'] = 'addproduct';
return view('products/add', $data);
}
I would like to know if it can be achieve with blade, or the best way to achieve that.
Thank you!
Option 1
You would have to write the select part of your form like this:
<div class="form-group">
<label for="#productCategory">Category:</label>
<select id="productCategory" class="form-control" name="category[]" multiple>
#foreach ($categories as $category)
<option value="{{ $category->id }}"{{ !empty(old('category')) && in_array($category->id, old('category')) ? ' selected="selected"' : '' }}>{{ $category->name }}</option>
#endforeach
</select>
</div>
Option 2
And arguably the more elegant solution is to install the html package from the laravel collective
composer require laravelcollective/html
follow the installation instructions on the laravel collective Forms & HTML documentation.
then just enter this where your select would be:
{!! Form::select('category[]', $categories, old('category'),['class' => 'form-control', 'multiple' => 'multiple'] ) !!}
Related
Whenever I visit the add-meeting URL, I receive an error message stating that $meeting is undefined. However, when I attempt to edit a meeting, everything works as expected. I am using the same blade file for both creating and updating meetings. Can you explain why this error is occurring?
Here is MeetingController:
public function add_meeting()
{
$customers = Customer::all();
$projects = Project::all();
return view('admin.meeting.add-meeting', get_defined_vars());
}
public function store(Request $request)
{
$this->validate($request, [
'meeting_scedule' => 'required',
'meeting_user_id' => 'required',
'project_id' => 'required',
'agenda' => 'required',
]);
if ($request->id) {
$input['meeting_scedule'] = $request->meeting_scedule;
$input['meeting_user_id'] = $request->meeting_user_id;
$input['project_id'] = $request->project_id;
$input['agenda'] = $request->agenda;
$meeting = Meeting::where('id', $request->id)->update($input);
return back()->with('success', 'Updated Successfully!');
} else {
$new['meeting_scedule'] = $request->meeting_scedule;
$new['meeting_user_id'] = $request->meeting_user_id;
$new['project_id'] = $request->project_id;
$new['agenda'] = $request->agenda;
$meeting = new Meeting();
$meeting->persist($new);
return back()->with('success', 'Meeting Created Successfully!');
}
}
public function edit_meeting($id)
{
$customers = Customer::all();
$projects = Project::all();
$meeting = Meeting::find($id);
return view('admin.meeting.add-meeting', get_defined_vars());
}
Here is add-meeting.blade.php file:
<form action="{{url('admin/update-meeting')}}" method="POST" id="add-rel-form"
enctype="multipart/form-data">
#csrf
#if(isset($meeting))
<input class="hidden" type="hidden" name="id" value="{{$meeting->id ?? ''}}">
#endif
<div class="form-row">
<div class="form-group col-md-6 mb-0">
<label> Meeting Schedule</label>
<div class="form-group">
<input type="datetime-local" value="{{$meeting->meeting_scedule ?? ''}}" required
class="form-control" name="meeting_scedule" id="meeting_scedule">
</div>
</div>
<div class="form-group col-md-6 mb-0">
<label> User</label>
<select id="customer-select" class='form-control' required name="meeting_user_id">
<option value="" id="">--Select User--</option>
#foreach($customers as $customer)
<option value="{{$customer->id}}"{{ $customer->id == $meeting->meeting_user_id ? 'selected' : '' }}>{{$customer->first_name." ".$customer->last_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
<label> Project</label>
<select id="project-select" class='form-control' required name="project_id" disabled>
<option value="" id="">--Select Project--</option>
#foreach($projects as $project)
<option value="{{$project->id}}"{{$project->id == $meeting->project_id ? 'selected' : ''}}>{{$project->project_type}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-6 mb-0">
<label> Agenda</label>
<div class="form-group">
<textarea type="text" value="" required
class="form-control" name="agenda" id="agenda">{{$meeting->agenda ?? ''}}</textarea>
</div>
</div>
</div>
Since there is no $meeting variable when creating a new meeting, the error occurs.
You can use null coalescing operator (??) or ternary operator (?:) to check if $meeting is defined before attempting to access its properties :
#if(isset($meeting))
<input class="hidden" type="hidden" name="id" value="{{$meeting->id}}">
#endif
...
<select id="customer-select" class='form-control' required name="meeting_user_id">
<option value="" id="">--Select User--</option>
#foreach($customers as $customer)
<option value="{{$customer->id}}" {{ isset($meeting) && $customer->id == $meeting->meeting_user_id ? 'selected' : '' }}>{{$customer->first_name." ".$customer->last_name}}</option>
#endforeach
</select>
...
<select id="project-select" class='form-control' required name="project_id" disabled>
<option value="" id="">--Select Project--</option>
#foreach($projects as $project)
<option value="{{$project->id}}"{{ isset($meeting) && $project->id == $meeting->project_id ? 'selected' : ''}}>{{$project->project_type}}</option>
#endforeach
</select>
...
<textarea type="text" value="" required class="form-control" name="agenda" id="agenda">{{ isset($meeting) ? $meeting->agenda : '' }}</textarea>
I have a search bar with 3 types of input and I want to search into my database if a data exist with those criteria.
Here is my html code for my search bar :
<form method="GET" action="{{ route('admin.liste.article.accueil.article') }}" class="mt-4 background_form">
<div class="form-row justify-content-center">
<div class="form-group col-md-4">
<label for="inputCity">Rechercher par ...</label>
<input class="form-control" name="rechercher" type="text" aria-label="Search" value="{{ request()->query('recherche') }}">
</div>
<div class="form-group col-md-2">
<label for="inputState">Type article</label>
<select id="inputState" class="form-control" name="type_article">
<option></option>
#foreach ($type_articles as $type_article)
<option value="{{ $type_article->type_article_id }}">{{ $type_article->libelle }}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-3">
<label for="datePublication">Date de publicaton</label>
<input class="form-control" type="text" placeholder="Exemple : 2021-02-29" name="date" value="{{ request()->query('date') }}">
</div>
<div class=" col-md-2 align-self-center mt-3">
<button type="submit" class="form-control btn-sm btn-custom mb-2">Trouver</button>
</div>
</div>
</form>
Into my controller :
public function accueil_article(Request $request)
{
$rechercher_par_accueil = $request->query('rechercher');
$type_article_rechercher_accueil = $request->query('type_article');
$date_publication_recherche_accueil = $request->query('date');
if($rechercher_par_accueil || $type_article_rechercher_accueil || $date_publication_recherche_accueil){
$article_rechercher = Article::where('titre', 'like', "%{$rechercher_par_accueil}%")
->when(request()->query('type_article_recherche'), function($query) {
$query->where('type_article_id', 'like', "%{$type_article_rechercher_accueil}%");
})
->when(request()->query('date_publication_recherche'), function($query) {
$query->where('created_at', 'like', "%{$date_publication_recherche_accueil}%");
})
->simplePaginate(5);
} else {
$article_rechercher = Article::orderBy('created_at','desc')->paginate(5);
}
return view('admin/article/admin_liste_article', [
'articles' => $article_rechercher,
'type_articles' => Type_article::all(),
'themes' => Theme::all()
]);
}
And at the bottom of my view, I've :
{!! $articles->appends(['rechercher' => request()->query('rechercher'), 'type_article' => request()->query('type_article'), 'date' => request()->query('date')])->links() !!}
Cordially
Try:
$query->whereIn('type_article_id', [$type_article_rechercher_accueil]);
I have the following lines for the create.blade.php (My Form)
<form action="/contact" method="POST">
<div class="form-control">
<fieldset>
<legend><span class="number">1</span> Personal Information</legend>
<input type="text" name="name" placeholder="Name *" value="{{old('name') }}">
<div>{{ $errors->first('name') }} </div>
<input type="text" name="email" placeholder="Phone *" value="{{old("email") }}">
<div>{{ $errors->first('email') }} </div>
<input type="text" name="phone" placeholder="Phone *" value="{{old('phone') }}">
<div>{{ $errors->first('phone') }} </div>
<label for="message">Message</label>
<textarea type="text" name="message" id="message" cols="30" rows="10">{{old('message') }}
</textarea>
<div>{{ $errors->first('message') }} </div>
<?php
$countries = array('India' => 'India',
'Pakistan' => 'Pakistan',
'Bosnia' => 'Bosnia',
'Andorra' => 'Andora',
'Haiti' => 'Haiti',
'Australia' => 'Australia',
'Maldives' => 'Maldives'
);
?>
<label for="message">Country</label>
<select name="country">
#foreach ($countries as $country)
<option value="{{ $country }}" #if(old('country') == $country) selected="selected" #endif>{{
$country }}</option>
#endforeach
</select>
#csrf
<button type="submit" class="btn btn-primary">Send message</button>
</div>
</form>
For my contact-form.blade.php (Mailable) I have the followig. This is supposed to show the submitted data in the email that I receive. The problem is I get all the data in input fields (Name, Number Email) BUT I dont get the selected country data. The problem most probably lies in the following lines.
#component('mail::message')
#Requested Information
<strong>Name</strong> {{ $data['name'] }}
<strong>Email</strong> {{ $data['email'] }}
<strong>Message</strong> {{ $data['message'] }}
<strong>Country</strong> {{ $data['$country'] }}
#endcomponent
The correct is $data['country'] not $data['$country'].
I think you are looking for the following code
$data=array(
'Name' => $request->name,
'email' => $request->email,
'country'=>$request->country,
'phone'=> $rwquest->phone,
);
Mail::send('here your email filename', $data, function($message) {
$message->subject(''); //subject of email
$message->from(); // sender email address
$message->to(); //receiver email
});
I have inserted the following line
$countries = $_POST['country'];
Now it looks like this
<select>
$countries = $_POST['country'];
#foreach ($countries as $country)
<option value="{{ $country }}" name="country"
#if(old('country') == $country) selected="selected"
#endif>
{{ $country }}</option>
#endforeach
</select>
Also the following line in my mailmake
Country {{ $data['country'] }}
I get the error undefined index:country
I am trying to insert with two tables with many to many relationship: Assignments and Collectors. I also make a intermediate or pivot table between them named assignment_collector.
create.blade.php in assignment folder
<form method="POST" action="{{ route('assignments.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="area_id">Area: </label>
<select class="form-control" name="area_id">
#foreach ($areas as $area)
<option value= "{{ $area->id }}">
{{ $area->campus }} {{ $area->building }} {{ $area->floor }}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="mts_id">MTS: </label>
<select class="form-control" name="mts_id">
#foreach ($mts as $mt)
<option value= "{{ $mt->id }}">
{{ $mt->location }}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<input type="hidden" class="form-control" id="status" name= "status" value="Active">
</div>
<div class="form-group">
<label for="collector_id">Collector: </label>
<select class="form-control" name="collector_id">
#foreach ($assignments as $assignment)
#foreach($assignment->collectors as $collector)
<option value= "{{ $collector->id }}">
{{ $collector->firstname }} {{ $collector->lastname }}
</option>
#endforeach
#endforeach
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</form>
AssignmentsController
public function store(Request $request)
{
$this->validate($request, [
'area_id' => 'required',
'mts_id' => 'required',
'status' => 'required',
'collector_id' => 'required'
]);
$assignment = new Assignment();
$assignment->area_id = $request->area_id;
$assignment->mts_id = $request->mts_id;
$assignment->status = $request->status;
$assignment->save();
$assignment_collector = new AssignmentCollector();
$assignment_collector->collector_id = $request->collector_id;
$assignment_collector->assignment_id = $assignment->id;
$assignment_collector->save();
return redirect('/assignments');
}
Assignment Model
public function collectors()
{
return $this->belongsToMany(Collector::class);
}
Collector Model
public function assignments()
{
return $this->belongsToMany(Assignment::class);
}
I got an error on this: App\AssignmentCollector since there is no AssignmentCollector and as I read the tutorials, you don't need to make a model for the pivot table. I reading the other articles but I get even more confused. Please help me because I'm still new in Laravel and I have get confused. Thanks!
You don't need a Model for your assignment collector table. What you want to do is create the Assignment then assign
$assignment->collectors()->create([
// all the collector data
]);
I can update text field of a form but i can not update checkbox field,option field and file field in Laravel 5.2. I i going to update then i can see all text value is perfectly shown in update blade view but in option field, checkbox field i see it is default value its don't comes from database. Again if i update with another option then its not saving.What i have tried so far:
My Controller:
public function update(Request $request, $id=0)
{
//
$id = $request->input("id");
$product = Product::find($id);
$product->product_name = $request->input('product_name');
$product->product_storage = $request->input('product_storage');
$product->product_percentage = $request->input('product_percentage');
$product->can_draw = $request->input('can_draw');
$product->real_price = $request->input('real_price');
$product->product_image = $request->input('product_image');
$product->save();
$request->session()->flash('alert-info', 'Product Successfully Updated!');
return Redirect::to('admin/product/all');
}
My update.blade.php View:
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('common.can_be_draw') }}</label>
<div class="col-md-9">
<div class="input-icon">
<i class="fa fa-money" aria-hidden="true"></i>
<select name="can_draw" class="form-control">
<option value="{{ $product->can_draw }}">{{ trans('common.open') }}open</option>
<option value="{{ $product->can_draw }}">{{ trans('common.close') }}close</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('common.real_prize') }}</label>
<div class="col-md-9">
<div class="input-icon">
<input type="radio" class="form-control" name="real_price" value="{{ $product->real_price }}"> {{ trans('common.yes') }}yes
<input type="radio" class="form-control" name="real_price" value="{{ $product->real_price }}" checked="checked"> {{ trans('common.no') }}no
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputFile" class="col-md-3 control-label">{{ trans('common.product_picture') }}</label>
<div class="col-md-9">
<input type="file" id="exampleInputFile" name="product_image" value="{{ $product->product_image }}">
<small>{{ trans('common.pic_summery') }}</small>
</div>
</div>
Just use this:
<input type="radio" {{$product->can_draw == 'Yes' ? 'checked' : ''}} class="form-control" name="real_price" value="Yes"> {{ trans('common.yes') }}yes
<input type="radio" {{$product->can_draw == 'Yes' ? '' : 'checked'}} class="form-control" name="real_price" value="No" > {{ trans('common.no') }}no
EDIT
I have edited the above*
You should change the value to Yes and No and use this to check if the value saved is Yes or No. It does not matter how much is real_price
your option field have same value ({{ $product->can_draw }})
<option value="value1"{{( $product->can_draw=='value1'?selected)}}>{{ trans('common.open') }}open</option>
<option value="value2 " {{( $product->can_draw=='value1'?selected)}}>{{ trans('common.close') }}close</option>
and for file field must use file not input:
$product->product_image = $request->file('product_image');
You just can save option value by requesting from select name.
In your example:
select name = "can_draw"
Just save value from request:
$product->can_draw = $request->can_draw;
For checkbox same:
$product->real_price = $request->real_price;
Not necessary indicate input() helper in request.
To retrieve all value for option and check box value, please use foreach methods:
#foreach($can_draws as $can_draw)
<option value="{{ $can_draw->id }}">{{ $can_draw->name}}</option>
#endforeach