I am working on a Laravel 4 project and I am trying to add a bunch of services to the services column in a simple service table. the columns are formatted as:
id userID services price
What I would like it to do is when a user selects the services all the services that user selects get's put into the services column to look like:
id userID services price
1 5 clean $4.95
2 5 unload $7.95
3 5 dance $1.95
4 5 vacuum $12.95
5 5 clean $4.95
basically all the services are in different input fields. So they aren't related.
I tried adding an array to the model but it gives an error:
Array to String conversion
Part of my Controller
$service = new Service();
$service->userID = $user->id;
$service->services = array(
Input::get('rooms'),
Input::get('pr_deodorizer'),
Input::get('pr_protectant') .
Input::get('pr_sanitzer'),
Input::get('fr_couch'),
Input::get('fr_chair'),
Input::get('fr_sectional'),
Input::get('fr_ottoman')
);
var_dump($service->services);die;
$service->save();
Laravel won't understand that you want to create various new instances of the model from just the array, so for each of the services, you'll have to create a separate instance of the Service model for each, eg.
$service = new Service();
$service->userID = $user->id;
$service->services = Input::get('rooms');
$service->save();
One idea.. perhaps you could group your services into a PHP array on your form using the square bracket notation:
<div>
<label for="room">Room</label>
<input type="text" id="room" name="services[]">
</div>
<div>
<label for="pr_deodorizer">Deodorizer</label>
<input type="text" id="pr_deodorizer" name="services[]">
</div>
<div>
<label for="pr_protectant">Protectant</label>
<input type="text" id="pr_protectant" name="services[]">
</div>
and then loop through the selected services in your Controller:
foreach(Input::get('services') as $service)
{
$service = new Service();
$service->userID = $user->id;
$service->services = $service;
$service->save();
}
... That's not tested, and I don't know what the format of your data is, but should give you a start on the problem..
Related
Help logically understand, I do not quite understand how you can implement this moment.
There is a form:
#foreach($weeks as $key => $value)
<li>
<label>
<input type="checkbox" value="{{$key}}" name="days[]"> {{$value}}
<div class="checkbox"></div>
</label>
<div class="time" data-day="mon">
<input type="time" name="start_time[]" class="start">
<span>-</span>
<input type="time" name="end_time[]" class="finish">
</div>
</li>
#endforeach
Images are attached to this form. My relationship is many to many.
In the request I get the following data:
images go to one table, days and times to another, intermediate between them. The problem is, I can't catch up with how to add data to the table with days. Since I get 3 arrays - days, start time and end.
I parsed the request in the controller. I add data to a table with an image.
$data = $request->validated();
$days[] = $data['days'];
$days[] = $data['start_time'];
$days[] = $data['end_time'];
unset($data['days'], $data['start_time'], $data['end_time']);
$image = Storage::disk('public')->put('/images', $data['image']);
$cover = DynamicCover::create([
'image' => $image,
'group_link' => $data['group_link'],
]);
The following data remains in the days array:
And here I am at a dead end, I don’t understand how to process them correctly, add them to the database and also fill in the link table
I will be grateful for advice. Many-to-many relationships, because there can be many images for one day, so this image will have many days
Still new to laravel, learning how the $request interacts with create.
here is my form for two of my variables for context:
<form method="POST" id="postForm">
{{-- #csrf --}}
<input type="hidden" id="id_hidden" name="id" />
<div class="form-group">
<label for="title"> Title <span class="text-danger">*</span></label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="category_description"> Description <span class="text-danger">*</span></label>
<textarea name="category_description" id="category_description" class="form-control"></textarea>
</div>
</form>
controller:
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'category_description' => 'required',
]);
$post = HmsBbrCategory::create($request->all());
if(!is_null($post)) {
return response()->json(["status" => "success", "message" => "Success! post created.", "data" => $post]);
}
else {
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
}
}
model:
protected $table = 'hms_bbr_category';
protected $fillable = [
"category_id", "title", "category_description", "category_description_2"
];
my title and category_description is inserting fine with an auto incremented id column. What I am trying to do is just to add 2 columns: category_id and category_description_2 that just copies the value inserted by id and category_description
Question:
how does 'required' retrieve the data from the form? I would like to have the same data thats taken and adding it to my two new columns. I am aware that I cannot just simple add 'category_description_2' => 'required',because this won't get an existing data.
so basically
$id = id
$category_id = id
$title = title
$category_description = category_description
$category_description_2 = category_description
1
Here is my table for reference. This form was given to me and I want to understand to know more about Laravel, thanks for reading and I hope I can get some suggestions on what to add.
You are running ->validate([]) on the $request variable which takes all of the information that is laravel puts together during the post request. If you do
dd($request->all()); you will be able to see all of the data that is passed from the form that you can run different validate rules on.
If you would like to add other data into your $request variable in order to save it to your model, you can always just add it to the $request array like so: $request['variable_1'] = 'data for variable one' and so on
Since I see that you have category_id that you would like to reference in your saved record, I would suggest you create a relation in your HmsBbrCategory model and the parent model that category_id belongs to. This will help you keep the integrity of your database in tact.
As another option, you can structure your url in such a way that passes the category_id to your store method in the controller. You will then need to find that category id and make sure it exists and save it via the relation that you created:
public function store (Request $request, $category_id){
$main_category = Category:find($category_id); //make sure it exists
$new_record = $main_category->exampleRelation()->save($request->all());
if(!$new_record){
return failed save
}
return successful save message
}
By doing the above, it will automatically insert the category_id into your saved record.
As another alternative, you could create a hidden field in your form that references category_id and other fields that you would like to add to your record on save. However, keep in mind which "sensitive" information you would like the users to see if someone decide to view source on the browser window.
Good afternoon colleagues ...
I need to be able to update another collection from a custom hook,
The following happens that if I use ItemsService or TableGatewayFactory it uses the acl of the container ... in this case the user will be from a customer role, but this does not have the permission to edit orders, I would like to keep it that way ...
It doesn't matter if I have to update the item with another user using their token, or any other alternative ...
Thanks in advance....
'item.update.transactionlog' => function ($data) { <br>
$container = Application::getInstance()->getContainer(); <br>
$itemsService = new \Directus\Services\ItemsService($container);<br>
$acl = $container->get('acl');<br>
$params = [];<br>
$orden = ['status' => 'paid'];<br>
$orderUpdate = $itemsService->update('orders', $data['orderid'], $orden, $params);<br>
}
I need your help with my situation in storing data.
I got a cart with several products, and now I want to store all these products in Order table at the same time by clicking submit button
My view blade.php
This view shows all products in the cart and I need to store these information in Ordertable
<form action="{{route('order.store')}}" method="post">
#csrf
#foreach ($cart as $ct)
<input type="text" name="product_id" value="{{$ct->id}}" hidden>
<input type="text" value="{{$ct->color}}" name="color" >
<input type="text" value="{{$ct->size}}" name="size" >
<input type="text" value="{{$ct->price}}" name="price" >
#endforeach
<button type="submit">submit</button>
</form>
In my Order table, I got these 4 columns need to fill in: product_id, color, size and price.
My foreach loop gets data from Cart table and all data were shown without errors.
My question is that How I can store these data to my Order table just by click on submit button once? What I should write in my store function in OrderController?
If my cart has 3 products then my expected value is the Order table will look like this:
id----product_id----size----color---price---+
---------------------------------------------
1 1 abc xyz 123
---------------------------------------------
2 2 abc2 xyz2 456
---------------------------------------------
3 3 aaa bbb 789
Thank for your help!
DB:
Order:
user_id
created_at
...
orderProducts:
price
color
size
order_id (relation)
product_id (relation)
...
View
<form action="{{route('order.store')}}" method="post">
#csrf
#foreach ($cart as $ct)
<input type="text" name="products[]" value="{{$ct->product_id}}" hidden>
<input type="text" value="{{$ct->color}}" name="color[]" >
<input type="text" value="{{$ct->size}}" name="size[]" >
<input type="text" value="{{$ct->price}}" name="price[]" >
#endforeach
<button type="submit">submit</button>
</form>
controller function store
$order= new Order;// change the model here
// .. complete your information's like user id or created_at
$order->save();
foreach($request->products as $key=>$product_id)
{
$product = Product::findOrFail($product_id); // validations the product id
// get your information's from db (color,size,price) don't trust get information's from user .
// $product->price , $product->color .... or get from cart
//from cart direct $color[$key] or $price[$key] or $size[$key] "I don't recomend to use this point"
// must be create new table
$orderProducts=new orderProducts; // create new table ordersProducts
$orderProducts->price = $product->price;
// .. complete your information's
$orderProducts->order_id = $order->id; // primary key
$orderProducts->product_id= $product->id;
$orderProducts->save();
}
Notice:
- You need to use try-catch to record info in order if fail in the step "findOrFail" or change to find and then if product not found in the table then record order not complete and show an error to the user
My Answer is quite similar to above answer but i would just like to put a different approach here with Database Transaction, Try Catch & Bulk Insert(to prevent placing queries in loop)
try {
DB::begintransaction();
$order = Order::create($orderData); // change the model here
$orderProductsData = [];
foreach($request->products as $product_id) {
$product = Product::find($product_id); // validations the product id
$orderProductsData[] = $tmpData = [
'price' => $product->price,
'order_id' => $order->id,
'product_id' => $product->id;
];
// must be create new table
// You can also store this way, but its still in loop so putting under comment.
// $orderProducts = orderProducts::create($tmpData);
}
orderProducts::insert($orderProductsData);
DB::commit();
} catch (Exception $e) {
DB::rollback();
thow $e; // modify with, How you handle your error response.
}
Again, Above answer is totally correct, However just putting a different approach, which i believe little more optimised way.
https://laracasts.com/lessons/laravel-5-and-behat-driving-authentication
This is the tutorial by Jeoffery Way that I am testing
This is the scenario that I am trying to test
Scenario: Adding a new school
When I add a new school with "Narendra School" "This is a cool school"
Then I should see "Add School"
And a school is created
This is my feature context file,
/**
* #When I add a new school with :arg1 :arg2
*/
public function iAddANewSchoolWith($name , $description )
{
$this->visit('school/create');
$this->fillField( 'name', $name );
$this->fillField( 'description', $description );
$this->pressButton('register');
}
/**
* #Then a school is created
*/
public function aSchoolIsCreated()
{
$school = School::all();
PHPUnit::assertEquals($school->isEmpty(), false );
}
This is my html code
<form method="post">
<h2>Add School</h2>
<input type="hidden" name="_token" value="{!! Session::getToken() !!}"/>
<input type="text" name="name" placeholder="Name">
<textarea name="description" placeholder="Description"></textarea>
<button name="register">Register</button>
</form>
This is the controller method that i am using to create the object
function create( ) {
if ( \Request::isMethod( 'post' ) ) {
$this->school->add( \Input::all() );// I am using a repository and dependency injection so this code is fine, it will add a school
}
return view('school::school.add');
}
When I hit the url, fill the form and hit register in the browser, I save a new school but when I run the test, I cannot seem to create the school.
The test is running I can see the html when I do a printLastResponse()
Feature: Testing
In order to teach Behat
As a teacher
I want to add a new school
Scenario: Adding a new school # features\example.feature:6
When I add a new school with "Narendra School" "This is a cool school" # FeatureContext::iAddANewSchoolWith()
Then I should see "Add School" # FeatureContext::assertPageContainsText()
And a school is created # FeatureContext::aSchoolIsCreated()
Failed asserting that false matches expected true.
--- Failed scenarios:
features\example.feature:6
1 scenario (1 failed)
3 steps (2 passed, 1 failed)
0m3.10s (26.24Mb)
This is my terminal log
What am I doing wrong?
You can try replace:
$this->pressButton('register');
With something like:
$page = $this->getSession()->getPage();
$buttonElement = $page->find('css',".//button[#name='register']");
$buttonElement->click();
When you use Selenium Driver, sometimes you can find clue in Selenium Server logs or at least see an exception when something goes wrong.
Also this would be better ;-)
PHPUnit::assertNotEmpty($school->isEmpty());