Call to a member function find() on array - laravel

"message": "Call to a member function find() on array",
"exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
How do I get the id parameter from the array below: When i pass the parameter 1 i want to fetch only first element when id is 2 I fetch item 2 of array
public function payments($id){
$data = [
['id' => 1, 'amount' => '22000', 'name' => 'ken'],
['id' => 2, 'amount' => '24000', 'name' => 'ken'],
['id' => 3, 'amount' => '26000', 'name' => 'ken'],
['id' => 4, 'amount' => '2000', 'name' => 'tom'],
];
return $data->find($id);
}

Since we're using a multi-dimensional array, we can use array_search with array_column.
$data = [
['id' => 1, 'amount' => '22000', 'name' => 'ken'],
['id' => 2, 'amount' => '24000', 'name' => 'ken'],
['id' => 3, 'amount' => '26000', 'name' => 'ken'],
['id' => 4, 'amount' => '2000', 'name' => 'tom'],
];
$key = array_search($id, array_column($data, 'id'));
echo var_dump($data[$key]);

If you want a "Laravel" alternative solution using collection
public function payments($id){
$data = [
['id' => 1, 'amount' => '22000', 'name' => 'ken'],
['id' => 2, 'amount' => '24000', 'name' => 'ken'],
['id' => 3, 'amount' => '26000', 'name' => 'ken'],
['id' => 4, 'amount' => '2000', 'name' => 'tom'],
];
$data = collect($data);
return $data->where('id', $id)->first();
}

public function payments($id){
$data = [
['id' => 1, 'amount' => '22000', 'name' => 'ken'],
['id' => 2, 'amount' => '24000', 'name' => 'ken'],
['id' => 3, 'amount' => '26000', 'name' => 'ken'],
['id' => 4, 'amount' => '2000', 'name' => 'tom'],
];
$data = collect($data);
return $data->where('id', $id)->all();
}

Related

yajra/laravel-datatables filterColumn doesnt work

Page loading correctly and every things work fine while bringing datas. Now I want to filter them but FilterColumn() method doesnt even work. When I tried filter() method it's working but then I won't get $keywords variable. I am missing something while querying leads ?
if (request()->ajax()) {
$leads = Lead::with('country','agent','detail')->orderBy('id','DESC');
$leads->where(function($q) use ($user){
if ($user->hasRole('agent') && !$user->hasRole('admin') && !$user->hasRole('lead')){ //agent isem
$q->where('agent_id',$user->id)
->orWhere('agent_id',null);
}
});
return DataTables::of($leads)->
addColumn('edit_button', function ($lead) {
$link = route('leads.edit',$lead->id);
return ' Edit ';
})->
filterColumn('edit_button', function ($query, $keyword) {
dd($keyword);
return $query->whereHas('patient', function ($query) use ($keyword) {
$query->whereRaw("CONCAT( name, ' ', surname ) like ?", ["%$keyword%"]);
});
})->rawColumns(['edit_button','phone','detail.conversion_notes'])->
toJson();
}
$tableColumn = [
['data' => 'edit_button', 'name' => 'edit_button', 'title' => 'Edit', 'searchable' => false],
['data' => 'full_name', 'name' => 'full_name', 'title' => 'Full Name'],
['data' => 'phone', 'name' => 'phone', 'title' => 'Phone'],
['data' => 'email', 'name' => 'email', 'title' => 'Email'],
['data' => 'country.name', 'name' => 'country.name', 'title' => 'Country'],
['data' => 'agent.name', 'name' => 'agent.name', 'title' => 'Agent'],
['data' => 'treatment', 'name' => 'treatment', 'title' => 'Treatment'],
['data' => 'find_us', 'name' => 'find_us', 'title' => 'Find Us'],
['data' => 'form_type', 'name' => 'form_type', 'title' => 'Form','visible' => false],
['data' => 'social_account', 'name' => 'social_account', 'title' => 'Sosyal Medya'],
['data' => 'created_at', 'name' => 'created_at', 'title' => 'Created At'],
['data' => 'detail.conversion_notes', 'name' => 'detail.conversion_notes', 'title' => 'Primary Notes'],
];
$html = $builder->columns($tableColumn)->parameters([
"pageLength" => 25,
"lengthMenu" => [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
'dom' => 'Bfrtip',
'columnDefs' => [
['width' => '2%', 'targets' => 0],
['width' => '7%', 'targets' => 1],
'buttons' => [
'pageLength',
[
'extend' => 'colvis',
'collectionLayout' => 'fixed two-column',
'columns' => ':not(.noVis)'
]
]
]);

Undefined Index in Laravel Migrate

I'm new to Laravel. I'm following this tutorial from LinkedIn Learning but I couldn't figure out how to make this work.
Basically, I need to insert new data in the menu_item model. In the tutorial, it uses Category model and they said that I have to create these four categories in the database.
It's very vague and I'm not sure what he means by "in the database", so I assume I should create Starters, Entree, Dessert and Salad columns in the Category model.
When I tried artisan migrate, it said it was successful but when I checked the mysql, I have no such columns! So I created them in mysql and they're there however when I tried to run composer dump-autoload and artisan db:seed --class=MenuItemsTableSeeder it didn't work. All I got was this error: ErrorException : Undefined index: Starters
I'm at loss on what to do.
Here is my menu-items from migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMenuItemsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('menu_items', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name', 128);
$table->string('description', 512);
$table->decimal('price');
$table->string('image');
$table->unsignedInteger('category_id');
$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('menu_items');
}
}
Here's my category model from migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('Starters');
$table->string('Salads');
$table->string('Entrees');
$table->string('Desserts');
$table->string('name');
$table->string('image');
$table->unsignedTinyInteger('display_order');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
And here's what I want to insert in the menu-item model where the errors occur starting from $startersId = $catIds['Starters'];:
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;
class MenuItemsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$categories = DB::select('select * from categories');
$catIds = [];
foreach ($categories as $cat) {
$catIds[$cat->name] = $cat->id;
}
$startersId = $catIds['Starters'];
$saladsId = $catIds['Salads'];
$entreesId = $catIds['Entrees'];
$dessertsId = $catIds['Desserts'];
DB::table('menu_items')->insert([
// Starters
[
'name' => 'Mini Cheeseburgers',
'category_id' => $startersId,
'image' => 'mini_cheeseburgers.jpg',
'description' => 'These mini cheeseburgers are served on a fresh baked pretzel bun with lettuce, tomato, avocado, and your choice of cheese.',
'price' => 8,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'French Onion Soup',
'category_id' => $startersId,
'image' => 'french_onion_soup.jpg',
'description' => 'Caramelized onions slow cooked in a savory broth, topped with sourdough and a provolone cheese blend. Served with sourdough bread.',
'price' => 7,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Artichokes with Garlic Aioli',
'category_id' => $startersId,
'image' => 'artichokes_with_garlic_aioli.jpg',
'description' => 'Our artichokes are brushed with an olive oil and rosemary blend and then broiled to perfection. Served with a side of creamy garlic aioli.',
'price' => 9,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Parmesan Deviled Eggs',
'category_id' => $startersId,
'image' => 'parmesan_deviled_eggs.jpg',
'description' => 'These delectable little bites are made with organic eggs, fresh Parmesan, and chopped pine nuts.',
'price' => 8,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
// Salads
[
'name' => 'Garden Buffet',
'category_id' => $saladsId,
'image' => 'parmesan_deviled_eggs.jpg',
'description' => 'Choose from our fresh local, organically grown ingredients to make a custom salad.',
'price' => 10,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'House Salad',
'category_id' => $saladsId,
'image' => 'house_salad.jpg',
'description' => 'Our house salad is made with romaine lettuce and spinach, topped with tomatoes, cucumbers, red onions and carrots. Served with a dressing of your choice.',
'price' => 7,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => "Chef's Salad",
'category_id' => $saladsId,
'image' => 'chefs_salad.jpg',
'description' => 'The chef’s salad has cucumber, tomatoes, red onions, mushrooms, hard-boiled eggs, cheese, and hot grilled chicken on a bed of romaine lettuce. Served with croutons and your choice of dressing.',
'price' => 9,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Quinoa Salmon Salad',
'category_id' => $saladsId,
'image' => 'quinoa_salmon_salad.jpg',
'description' => 'Our quinoa salad is served with quinoa, tomatoes, cucumber, scallions, and smoked salmon. Served with your choice of dressing.',
'price' => 12,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
// Entrees
[
'name' => 'Classic Burger',
'category_id' => $entreesId,
'image' => 'classic_burger.jpg',
'description' => 'Our classic burger is made with 100% pure angus beef, served with lettuce, tomatoes, onions, pickles, and cheese of your choice. Veggie burger available upon request. Served with French fries, fresh fruit, or a side salad.',
'price' => 10,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Tomato Bruschetta Tortellini',
'category_id' => $entreesId,
'image' => 'tomato_bruschetta_tortellini.jpg',
'description' => 'This classic cheese tortellini is cooked in a sundried tomato sauce. Served with bruschetta topped with a tomato and basil marinara.',
'price' => 14,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Handcrafted Pizza',
'category_id' => $entreesId,
'image' => 'handcrafted_pizza.jpg',
'description' => 'Our thin crust pizzas are made fresh daily and topped with your choices of fresh meats, veggies, cheese, and sauce. Price includes two toppings. Add $1 for each additional topping.',
'price' => 10,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Barbecued Tofu Skewers',
'category_id' => $entreesId,
'image' => 'barbecued_tofu_skewers.jpg',
'description' => 'Our barbecued skewers include tofu, cherry tomatoes, bell peppers, and zucchini marinated in a ginger sesame sauce and charbroiled. Served with steamed rice.',
'price' => 10,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Fiesta Family Platter',
'category_id' => $entreesId,
'image' => 'fiesta_family_platter.jpg',
'description' => 'This platter is perfect for sharing! Enjoy our spicy buffalo wings, traditional nachos, and cheese quesadillas served with freshly made guacamole dip.',
'price' => 16,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
// Desserts
[
'name' => 'Crème Brûlée',
'category_id' => $dessertsId,
'image' => 'creme_brulee.jpg',
'description' => 'Elegantly crafted creamy vanilla custard with a caramelized crunchy layer on top. Served with seasonal fruit.',
'price' => 9,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Cheesecake',
'category_id' => $dessertsId,
'image' => 'cheesecake.jpg',
'description' => 'Our New York Style Cheesecake is rich, smooth, and creamy. Available in various flavors, and with seasonal fruit toppings.',
'price' => 9,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Chocolate Chip Brownie',
'category_id' => $dessertsId,
'image' => 'chocolate_chip_brownie.jpg',
'description' => 'A warm chocolate chip brownie served with chocolate or vanilla ice cream and rich chocolate sauce.',
'price' => 6,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Apple Pie',
'category_id' => $dessertsId,
'image' => 'apple_pie.jpg',
'description' => 'Made with local granny smith apples to bring you the freshest classic apple pie available.',
'price' => 5,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Mixed Berry Tart',
'category_id' => $dessertsId,
'image' => 'mixed_berry_tart.jpg',
'description' => 'Raspberries, blueberries, and strawberries on top of a creamy filling served in a crispy tart.',
'price' => 7,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
]);
}
}
You have added the categories 'Starters','Salads','Entrees','Desserts' in your categories table as columns.
Create a seeder for Categories Table and add these values in name columns.
Update the migration for categories :
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('image')->nullable(); // if you do not have images path in seeder
$table->unsignedTinyInteger('display_order');
$table->timestamps();
});
Add the categories table seeder
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;
class CategoriesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('categories')->insert([
[
'name' => 'Starters',
'image' => 'image_path',
'display_order' => 1,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Salads',
'image' => 'image_path',
'display_order' => 2,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Entrees',
'image' => 'image_path',
'display_order' => 3,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
[
'name' => 'Desserts',
'image' => 'image_path',
'display_order' => 4,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
]);
}
}

Can't call model method in toSearchableArray array when created via factory

I am trying to get a model factory to work, the main model Venue the following:
Place which is a hasOne relation
Type which has a belongsTo relation
On top of that, place has a function called full_address, that returns a comma separated string.
The Venue has a toSearchableArray() to send custom data to Algolia, when I run the factory create method I get:
PHP Error: Call to a member function full_address() on null in app/Venue.php on line 57
This is the venue Model
class Venue extends Model
{
use Searchable;
public function toSearchableArray()
{
$type = $this->type()->first();
$place = $this->place()->first();
return [ 'name' => $this->name,
'type' => $type['name'],
'type_id' => $type['id'],
'venue_id' => $this->id,
'background_image' =>$type['background_file_name'],
'full_address' => $place->full_address(),
'slug' => $this->slug_field,
'_geoloc' =>
[ 'lat' => (float)$this->latitude,
'lng' => (float)$this->longitude
]
];
}
public function place()
{
return $this->hasOne('App\Place');
}
public function type()
{
return $this->belongsTo('App\Type');
}
}
And these are the model factories
$factory->define(App\Venue::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'phoneNumber' => $faker->word,
'latitude' => $faker->latitude,
'longitude' => $faker->longitude,
'LatLong' => $faker->word,
'website' => $faker->word,
'type' => $faker->word,
'place_id' => function () {
return factory(App\Place::class)->create()->id;
},
'status' => $faker->word,
'slug_field' => $faker->word,
'type_id' => function () {
return factory(App\Type::class)->create()->id;
},
];
});
$factory->define(App\Place::class, function (Faker\Generator $faker) {
return [
'place_id' => $faker->randomNumber(),
'administrative_area_level_2' => $faker->word,
'administrative_area_level_1' => $faker->word,
'country' => $faker->country,
'postal_town' => $faker->word,
'postal_code_prefix' => $faker->word,
'postal_code' => $faker->word,
'route' => $faker->word,
'locality' => $faker->word,
'premise' => $faker->word,
'street_number' => $faker->word,
'neighborhood' => $faker->word,
'point_of_interest' => $faker->word,
'natural_feature' => $faker->word,
'administrative_area_level_3' => $faker->word,
'postal_code_suffix' => $faker->word,
'sublocality_level_1' => $faker->word,
'subpremise' => $faker->word,
'sublocality_level_5' => $faker->word,
'sublocality_level_4' => $faker->word,
'sublocality_level_2' => $faker->word,
'sublocality_level_3' => $faker->word,
'administrative_area_level_4' => $faker->word,
'colloquial_area' => $faker->word,
'long' => '123',
'lat' => '123',
];
});
$factory->define(App\Type::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'marker_file_name' => $faker->word,
'background_file_name' => $faker->word,
'description' => $faker->word,
'ShortName' => $faker->word,
];
});
what do I need to do in order to get a reference to the place that is associated with the venue.
Thanks

issue getting correct output with nested collection

Nested:
$collection = collect([
'result' => [
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100]
],
]);
$filtered = $collection->where('price', 100);
$filtered->all();
Not Nested:
$collection = ([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);
$filtered->all();
I can get this output when the above is not nested with result, how can i get the same output nested with result?
/*
[
['product' => 'Chair', 'price' => 100],
['product' => 'Door', 'price' => 100],
]
*/
What if you filter on result key of collection
$filtered = $collection.result->where('price', 100);
I figured out what I needed to do. I just created a new variable:
$collection1 = collect($collection['result']);
which seemed to resolve my issue.

These credentials do not match our records

I have an app with laravel in which, I have different users and different roles. I insert some users, roles, role_user, permission and permission_role in my DB using seeder but, when I try to login using email and password already recorded in DB, I got : These credentials do not match our records.
this is UserTableSeeder :
public function run()
{
//
$user = [
[
'name' => 'admin',
'email' => 'admin#mail.co',
'password' => 'passwordadmin'
],
[
'name' => 'president',
'email' => 'President#mail.co',
'password' => 'passwordpresident'
],
[
'name' => 'utilisateur1',
'email' => 'utilisateur1#mail.co',
'password' => 'passworduser'
],
[
'name' => 'utilisateur2',
'email' => 'utilisateur2#mail.co',
'password' => 'passworduser'
]
];
foreach ($user as $key => $value) {
User::create($value);
}
}
RoleTableSeeder :
public function run()
{
//
$role = [
[
'name' => 'admin',
'display_name' => 'Administrateur',
'description' => 'Administrateur du système'
],
[
'name' => 'president',
'display_name' => 'Président',
'description' => 'President de la commune'
],
[
'name' => 'utilisateur_normal',
'display_name' => 'membre du conseil',
'description' => 'membre du conseil'
]
];
foreach ($role as $key => $value) {
Role::create($value);
}
}
RoleUserTableSeeder :
public function run()
{
//
DB::table( 'role_user' )->insert([
[ 'user_id' => 6, 'role_id' => 4 ],
[ 'user_id' => 7, 'role_id' => 5 ],
[ 'user_id' => 8, 'role_id' => 6 ],
[ 'user_id' => 9 , 'role_id' => 6 ],
]);
}
Models I have : User, Role, Permission.
Any idea please ?
It looks you are not hashing your passwords into your database, you need to use bycript:
public function run()
{
//
$user = [
[
'name' => 'admin',
'email' => 'admin#mail.co',
'password' => bcrypt('passwordadmin')
],
[
'name' => 'president',
'email' => 'President#mail.co',
'password' => bcrypt('passwordpresident')
],
[
'name' => 'utilisateur1',
'email' => 'utilisateur1#mail.co',
'password' => bcrypt('passworduser')
],
[
'name' => 'utilisateur2',
'email' => 'utilisateur2#mail.co',
'password' => bcrypt('passworduser')
]
];
foreach ($user as $key => $value) {
User::create($value);
}
}
You can see more seeder examples on the oficial seeder Laravel documentation.
As Troyer said, you need to hash them with bcrypt. Laravel provides a handy wrapper with \Hash::make($str).
It is extremely bad practice to have your passwords in plaintext.
You need to run your seeder like this:
public function run()
{
$users = [
[
'name' => 'admin',
'email' => 'admin#mail.co',
'password' => \Hash::make('passwordadmin') // Hash them in order to make use of \Auth library (and more importantly, in order not to be a dick to your users)
],
[
'name' => 'president',
'email' => 'President#mail.co',
'password' => \Hash::make('passwordpresident')
],
[
'name' => 'utilisateur1',
'email' => 'utilisateur1#mail.co',
'password' => \Hash::make('passworduser')
],
[
'name' => 'utilisateur2',
'email' => 'utilisateur2#mail.co',
'password' => \Hash::make('passworduser')
]
];
User::create($users); // Import them with 1 query for performance
}

Resources