I want to update/insert my parent directly with my child instead of separated them. After my validation rule has passed.
my code:
$validatedData = $request->validate([
'id' => 'bail|integer',
'code' => 'bail|integer',
'name' => 'bail|required|string|max:255',
'child' => 'bail|array',
'child.something' => 'bail|integer',
]);
$parent = Parent::updateOrCreate(['id' => $request->id, 'code' => $request->code], $validatedData);
You can't. You need to update the child after the parent is successfully updated.
Related
I implement the InlineCreate Operation in Backpack for Laravel and works fine, but my field depend of other field and I can't to get the parent field information in the modal or in the setup operation.
Field Definition
$this->crud->addField([
'name' => 'cliente_contacto',
'type' => "relationship",
'ajax' => true,
//'inline_create' => true,
'inline_create' => [ // specify the entity in singular
'entity' => 'cliente_contacto', // the entity in singular
// OPTIONALS
'force_select' => true, // should the inline-created entry be immediately selected?
'modal_class' => 'modal-dialog modal-lg', // use modal-sm, modal-lg to change width
'modal_route' => route('cliente-contacto-inline-create'), // InlineCreate::getInlineCreateModal()
'create_route' => route('cliente-contacto-inline-create-save'), // InlineCreate::storeInlineCreate()
'include_main_form_fields' => ['proyecto'] // pass certain fields from the main form to the modal
],
// 'data_source' => backpack_url('presupuesto/fetch/cliente-contacto'),
// 'placeholder' => 'Seleccione un elemento',
'minimum_input_length' => 0,
'dependencies' => ['cliente'], // when a dependency changes, this select2 is reset to null
//'method' => 'POST', // optional - HTTP method to use for the AJAX call (GET, POST)
//'include_all_form_fields' => true, //sends the other form fields along with the request so it can be filtered.
'tab' => 'Datos Principales',
'wrapper' => [
'class' => 'col-md-3'
]
]);
ClienteContactoCrudController
protected function setupInlineCreateOperation()
{
$parent_loaded_fields = request()->get('parent_loaded_fields');
}
But I can't get that fields.
The documentation:
https://backpackforlaravel.com/docs/5.x/crud-operation-inline-create#how-to-use-1
'include_main_form_fields' => ['field1', 'field2'], // pass certain fields from the main form to the modal
Don't said how get that values.
I found this: https://github.com/Laravel-Backpack/CRUD/issues/2925#issuecomment-644060749
I can get:
'entity' => request()->get('entity'),
'modalClass' => request()->get('modal_class'),
But
'parentLoadedFields' => request()->get('parent_loaded_fields')
Don't work
How can I get de parent field values?
you should get them with request('main_form_fields').
I've just submitted a PR to the docs to reference that: https://github.com/Laravel-Backpack/docs/pull/341
Cheers
So I am new to laravel. I am trying to use a view but it keeps referencing its self with links.
See below what I mean
So I have a route "customers"
Route::get('customers/{cid?}', [
'uses' => 'customers#getCustomerView'
])->name('customers');
In this route as you can see I reference a controller getCustomerView. With an optional CID as someone might just want to see a list of customers. Then choose their customer. So here is the controller function
public function getCustomerView($cid = null){
$activeCustomer = array();
if(!empty($cid)){
// do middleware to get customer active detail
$activeCustomer = array(
'company' => 'Company '.$cid,
'fname' => 'Test',
'lname' => 'test'
);
}
return view('customers.view', [
'title' => 'Customer List',
'cid' => $cid,
'activeCustomer' => $activeCustomer,
'clist' => [
['company'=>'Company 1', 'fname' => 'Bob', 'lname' => 'Smith'],
['company'=>'Company 2', 'fname' => 'Julie', 'lname' => 'Reid'],
['company'=>'Company 3', 'fname' => 'Tony', 'lname' => 'Tima']
]
]);
}
When I load http://domain/customers - Everything works fine.
In my customers.view I have the following that loops and put's the array into a table. Later I will be using some middle ware or self function to get data from database. For now I am just using a harden array.
#foreach($clist as $key=>$customer)
<tr>
<td>{{$key+1}}</td>
<td>{{$customer['company']}}</td>
<td>{{$customer['fname']}}</td>
<td>{{$customer['lname']}}</td>
</tr>
#endforeach
The problem lies. Once I click on a customer. Page loads fine. http://domain/customers/1 - But if I go to click on another customer it does this
http://domain/customers/1/customers/2 - obviously this would cause an error. So why is it doing this?
How can I prevent it?
use this :
<td>{{$customer['company']}}</td>
it will generate a full url like http://domain/customers/1
but you can simply do that :
<td>{{$customer['company']}}</td>
Could you please help me to handle this.
Controller:
$ad = Ad::create([
'title' => request('title'),
'body' => request('body'),
'cat_title' => $cat->title,
'price' => request('price'),
'city' => request('city')
]);
$cat = Category::create([
'title' => request('category'),
'slug' => str_slug(request('category'), '-'),
'ad_id' => $ad->id
]);
I'm getting an error - Undefined variable: cat - obviously? Since the $cat variable is not yet defined on the time of being requested? But how could I handle this? And generally - am I doing it pretty much right?
My ad belongsTo category, and category hasMany ads.
Thank you!
You are executing your 2nd portion after the insertion of the ad so, you can wrap it inside a condition something like this.
// Execute this portion if above statement executed succesfully.
if (!empty($ad->id)) {
$cat = Category::create([
'title' => request('category'),
'slug' => str_slug(request('category'), '-'),
'ad_id' => $ad->id
]);
}
Laravel 4.1. I want to update a city, check the rules and it fails on unique check.
Rules:
public static $rules = [
'name' => 'required|alpha_dash|unique:cities',
'slug' => 'alpha_dash|unique:cities',
'seo_title' => 'required|max:60|unique:cities',
'seo_description' => 'required|max:160|unique:cities',
'rank' => 'integer',
'visible' => 'integer'
];
I know, I can smth like:
'name' => 'required|alpha_dash|unique:cities, name, ##',
where ## - id, but I cant dynamically set id to updated one.
'name' => "required|alpha_dash|unique:cities, name, $id", // doesnt work
'name' => "required|alpha_dash|unique:cities, name, $this->id", // doesnt work
Is there any way to do it normally ?
You can do it in separate ways.
An easy way is to use different rules based on different actions . When you will create the model, you will use the rules that you currently have.
When you will update the model, you will change the unique:cities to exists:cities
I usually do this with a validation service.
You create a base abstract Validator in services/ , which has a passes() function.
For each model, you create a ModelValidator , in your case CityValidator. Where you put your rules like :
public static $rules = [
'new'=>[
'name' => 'required|alpha_dash|unique:cities',
'slug' => 'alpha_dash|unique:cities',
'seo_title' => 'required|max:60|unique:cities',
'seo_description' => 'required|max:160|unique:cities',
'rank' => 'integer',
'visible' => 'integer'],
'edit'=>[
'name' => 'required|alpha_dash|exists:cities',
'slug' => 'alpha_dash|unique:cities',
'seo_title' => 'required|max:60|exists:cities',
'seo_description' => 'required|max:160|exists:cities',
'rank' => 'integer',
'visible' => 'integer'
]
];
The 3rd argument accepts a value to be ignored... If you want to do a WHERE clause, do it like:
'name' => array("required", "alpha_dash", "unique:cities,name,null,id,id,$this->id"...
The docs says:
Adding Additional Where Clauses
You may also specify more conditions that will be added as "where"
clauses to the query:
'email' => 'unique:users,email_address,NULL,id,account_id,1'
In the rule above, only rows with an account_id of 1 would be included in the unique check.
Learn by example:
email => unique:users,email_address,id,NULL,field_1,value_1,field_2,value_2,field_x,value_x
Generates the query:
SELECT
count(*) AS AGGREGATE
FROM
`entries`
WHERE
`email_address` = ?
AND `id` <> NULL
AND `field_1` = `value_1`
AND `field_2` = `value_2`
AND `field_x` = `value_x`
I found an elegant-ish way to do this using fadion/ValidatorAssistant:
<?php
use Fadion\ValidatorAssistant\ValidatorAssistant;
class CityValidator extends ValidatorAssistant {
// standard rules
public static $rules = [
'name' => 'required|alpha_dash',
'slug' => 'alpha_dash',
'seo_title' => 'required|max:60',
'seo_description' => 'required|max:160',
];
// some preparation before validation
protected function before()
{
// Inject the given city id into the unique rules
$this->rules['name'] .= 'unique:cities,name,' . $this->inputs['id'];
$this->rules['slug'] .= 'unique:cities,slug,' . $this->inputs['id'];
$this->rules['seo_title'] .= 'unique:cities,seo_title,' . $this->inputs['id'];
$this->rules['seo_description'] .= 'unique:cities,seo_description,' . $this->inputs['id'];
}
There's almost certainly a more elegant way to do this when you need several fields to be unique database-wide, but the above works very well for times when you only need one part to be unique.
I'm not sure if the title of this question is necessarily the accurate description of what I need to do, but I'll go ahead and ask my question and see what everyone thinks...
Basically, I am receiving data from a source that I have no control over, and I need to transpose it into a suitable format for inserting into my database using CakePHP. So, here's how I'm doing it:
public function submitApp($data) {
$array = array(
'Student' => array(
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'address' => $data['address'],
'dob' => $data['dob'],
'gender' => $data['gender']
),
'Application' => array(
'course_id' => $data['course_id'],
'question1' => $data['question1'],
'question2' => $data['question2'],
'question3' => $data['question3'],
'question4' => $data['question4'],
),
'ApplicationQualification' => $data['Qualifications']
);
// Logic to save $array goes here
}
The problem is that sometimes not all of the keys in $data will be submitted to my app but I still want my app to work with what it gets.
I know that I can wrap each key in a conditional like this:
if (!isset($data['name'])) { $data['name'] = null; }
...and then building the array, but this seems like a pretty clumsy way of doing it. Is there a more efficient way to do this?
You could use a simple ternary statement
'name' => array_key_exists('name', $data) ? $data['name'] : null
Alternatively, you can set up a default array and then merge the given values in
$defaults = [
'name' => null,
'email' => null,
// etc
];
$data = array_merge($defaults, $data);