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
]);
}
Related
I have two factories one for categories and another for products. When I run the factory I want to create x number of products for each category generated. how would I write the code to product this?
the definition for the categories is written as this:
return [
'name' => $this->faker->word,
'slug' => Str::slug($this->faker->unique()->word, '-'),
];
and the definition for the product is written as such:
return [
'category_id' => 1, //instead of 1 the category id used i want to be random
'name' => $this->faker->word,
'slug' => Str::slug($this->faker->unique()->word, '-'),
'description' => $this->faker->paragraph,
'price' => $this->faker->randomFloat(2, 0, 10000),
'is_visible' => 1,
'is_featured' => 1
];
as you can see I hardcoded the category_id, I wasnt too sure how to have it automatically generate and create a product per category that exists. I have the factory for the category written as this, to create 10 items
Category::factory()
->count(10)
->create();
I tried this for trial and error thinking it would work but I get an error that category_id cannot be null .
Product::factory()
->has(Category::factory()->count(2))
->count(20)
->create();
$factory->define(Product::class, function (Faker $faker) {
return [
'category_id' => factory(Category::class), //instead of 1 the category id used i want to be random
'name' => $this->faker->word,
'slug' => Str::slug($this->faker->unique()->word, '-'),
'description' => $this->faker->paragraph,
'price' => $this->faker->randomFloat(2, 0, 10000),
'is_visible' => 1,
'is_featured' => 1
];
});
By setting the attribute to an instance of factory() Laravel will lazily create that model as well and automatically associate it
I am using kind of different syntax, but I think it will work / you can change it
In your Category.php model
public function products() {
return $this->hasMany(Product::class);
}
In seeder
factory(App\Category::class, 10)->create()->each(function($c) {
$c->products()->save(factory(App\Product::class)->make());
}); // each Category will have 1 product
Laravel Database Testing Relationships
You simply need to pass a CategoryFactory to category_id.
return [
'category_id' => Category::factory(),
// ...
];
You can read more about factories here: https://laravel.com/docs/8.x/database-testing#defining-relationships-within-factories
If you want to create multiple products per each created category, you can do something like this:
// CategoryProductSeeder
$categories = Category::factory(50)->create();
$categories->each(function ($category) {
$categories->products()->saveMany(
Product::factory(10)->make()
);
});
this is what worked for me since I'm using laravel 8.
product definition:
return [
'category_id' => Category::factory(),
'name' => $this->faker->word,
'slug' => Str::slug($this->faker->unique()->word, '-'),
'description' => $this->faker->paragraph,
'price' => $this->faker->randomFloat(2, 0, 1000),
'is_visible' => 1,
'is_featured' => 1
];
seeder:
Product::factory()
->has(Category::factory())->count(50)
->create();
created 50 categories and 50 products. 1 category assigned to each product.
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>
I created this array of objects:
$ad_1 = new AdUnit(array('id' => '1', 'name' => 'Ad_1', 'description' => 'great ad', 'code' => 'alpha', 'widget_id' => '123'));
$ad_2 = new AdUnit(array('id' => '2', 'name' => 'Ad_2', 'description' => 'good ad', 'code' => 'delta', 'widget_id' => '456'));
$ad_3 = new AdUnit(array('id' => '3', 'name' => 'Ad_3', 'description' => 'bad ad', 'code' => 'sigma', 'widget_id' => '789'));
$adUnitArr = array($ad_1, $ad_2, $ad_3);
and i want to check that a random ad i got from a function exists in the array. the code to get the ad looks like this:
$fixture = new AdGroup();
$fixture->setAds($adUnitArr);
$randad = $fixture->getRandomAd();
now i want to check if the array contains the random ad i received, what i was able to do like this:
$this->assertEquals(in_array($randad, $adUnitArr), 1); //check if ad in array
but my question is, is there an assert or some other way to check this thing better than the way i did it?? i tried using assertArrayHasKey but i got the following error:
PHPUnit_Framework_Exception: Argument #1 (No Value) of PHPUnit_Framework_Assert::assertArrayHasKey() must be a integer or string
any idea please? thx
Try the assertContains method:
$this->assertContains( $randad, $adUnitArr );
I had asked a question here a while back about setting up database populated dropdowns for SugarCRM. I received a really good answer and, after more php studies and a dev instance running, I decided to give it a shot. The instructions I followed can be found here. After I run the repair and rebuild, I would expect to see the custom field in my Fields list under the module in studio, but have not been able to find it. The module is named Makers (a1_makers as a database table). For good orders sake, there were no errors when I repaired/rebuilt after saving the files. Per the instructions, I first created a php file with a custom function to query the database (custom/Extension/application/Ext/Utils/getMakers.php):
<?php
function getMakers() {
static $makers = null;
if (!$makers){
global $db;
$query = "SELECT id, name FROM a1_maker";
$result = $db->query($query, false);
$accounts = array();
$accounts[''] = '';
while (($row = $db->fetchByAssoc($result)) !=null) {
$accounts[$row['id']] = $row['name'];
}
}
return $makers;
}
?>
Then, I set 'function' field in Vardefs to point to the function (custom/Extension/modules/Maker/Ext/Vardefs/makers_template.php):
<?php
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'len' => '100',
'comment' => 'List of makers populated from the database',
);
?>
Unfortunately, there are no errors and the repair/rebuild runs fine. I am just unable to see the custom field when I go into studio. Can anyone please help point out what I may be doing wrong?
I would recommend checking existence of newly created field 'list_of_makers' in cache/modules/Maker/Makervardefs.php file. If new field definition exists in that file, try add 'studio' => 'visible' to custom/Extension/modules/Maker/Ext/Vardefs/makers_template.php to get something like this:
<?php
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'studio' => 'visible'
'len' => '100',
'comment' => 'List of makers populated from the database',
);
Try to edit your custom/modules/Maker/metadata/editviewdefs.php manually and insert field definition by hand in proper place if everything above won't work.
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'studio' => 'visible'
'len' => '100',
'comment' => 'List of makers populated from the database',
'studio' => array(
'listview' => true,
'detailview' => true,
'editview' => true
),
);
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);