Ошибка call to a member function on array

I’m trying to get the products from my selection in the Category object but I gives me the following error

Error: Call to a member function getProducts() on array in
/Users/jurrejan/Documents/projects/audsur2/src/Audsur/ShopBundle/Controller/DefaultController.php
line 94

Where am I going wrong?

The object has multiple products

array(1) {
  [0]=>
  object(stdClass)#329 (6) {
    ["__CLASS__"]=>
    string(33) "AudsurShopBundleEntityCategory"
    ["id"]=>
    int(4)
    ["name"]=>
    string(8) "Receiver"
    ["slug"]=>
    string(8) "receiver"
    ["description"]=>
    string(5) "descr"
    ["products"]=>
    array(47) {
      [0]=>
      string(32) "AudsurShopBundleEntityProduct"
      [1]=>
      string(32) "AudsurShopBundleEntityProduct"
      [2]=>
      string(32) "AudsurShopBundleEntityProduct"
      [3]=>
      string(32) "AudsurShopBundleEntityProduct"
      [4]=>
      string(32) "AudsurShopBundleEntityProduct"
      [5]=>
      string(32) "AudsurShopBundleEntityProduct"
      [6]=>
      string(32) "AudsurShopBundleEntityProduct"
      [7]=>
      string(32) "AudsurShopBundleEntityProduct"
      [8]=>
      string(32) "AudsurShopBundleEntityProduct"
      [9]=>
      string(32) "AudsurShopBundleEntityProduct"
      [10]=>
      string(32) "AudsurShopBundleEntityProduct"
      [11]=>
      string(32) "AudsurShopBundleEntityProduct"
      [12]=>
      string(32) "AudsurShopBundleEntityProduct"
      [13]=>
      string(32) "AudsurShopBundleEntityProduct"
      [14]=>
      string(32) "AudsurShopBundleEntityProduct"
      [15]=>
      string(32) "AudsurShopBundleEntityProduct"
      [16]=>
      string(32) "AudsurShopBundleEntityProduct"
      [17]=>
      string(32) "AudsurShopBundleEntityProduct"
      [18]=>
      string(32) "AudsurShopBundleEntityProduct"
      [19]=>
      string(32) "AudsurShopBundleEntityProduct"
      [20]=>
      string(32) "AudsurShopBundleEntityProduct"
      [21]=>
      string(32) "AudsurShopBundleEntityProduct"
      [22]=>
      string(32) "AudsurShopBundleEntityProduct"
      [23]=>
      string(32) "AudsurShopBundleEntityProduct"
      [24]=>
      string(32) "AudsurShopBundleEntityProduct"
      [25]=>
      string(32) "AudsurShopBundleEntityProduct"
      [26]=>
      string(32) "AudsurShopBundleEntityProduct"
      [27]=>
      string(32) "AudsurShopBundleEntityProduct"
      [28]=>
      string(32) "AudsurShopBundleEntityProduct"
      [29]=>
      string(32) "AudsurShopBundleEntityProduct"
      [30]=>
      string(32) "AudsurShopBundleEntityProduct"
      [31]=>
      string(32) "AudsurShopBundleEntityProduct"
      [32]=>
      string(32) "AudsurShopBundleEntityProduct"
      [33]=>
      string(32) "AudsurShopBundleEntityProduct"
      [34]=>
      string(32) "AudsurShopBundleEntityProduct"
      [35]=>
      string(32) "AudsurShopBundleEntityProduct"
      [36]=>
      string(32) "AudsurShopBundleEntityProduct"
      [37]=>
      string(32) "AudsurShopBundleEntityProduct"
      [38]=>
      string(32) "AudsurShopBundleEntityProduct"
      [39]=>
      string(32) "AudsurShopBundleEntityProduct"
      [40]=>
      string(32) "AudsurShopBundleEntityProduct"
      [41]=>
      string(32) "AudsurShopBundleEntityProduct"
      [42]=>
      string(32) "AudsurShopBundleEntityProduct"
      [43]=>
      string(32) "AudsurShopBundleEntityProduct"
      [44]=>
      string(32) "AudsurShopBundleEntityProduct"
      [45]=>
      string(32) "AudsurShopBundleEntityProduct"
      [46]=>
      string(32) "AudsurShopBundleEntityProduct"
    }
  }
}

Controller

<?php

namespace AudsurShopBundleController;

use SymfonyBundleFrameworkBundleControllerController;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SensioBundleFrameworkExtraBundleConfigurationTemplate;

use AudsurShopBundleEntityCategory;
use AudsurShopBundleEntityBrand;
use AudsurShopBundleEntityProduct;
use SymfonyComponentHttpFoundationResponse;

class DefaultController extends Controller
{
    /* removed irrelevant functions */

    public function getGroupAction($slug, $type = null, $grouped = true)
    {

        $group = $this->getDoctrine()
            ->getRepository('AudsurShopBundle:'.$type)
            ->findBy(array( 'name' => $slug ))
            ->getProducts();


        return $this->render('AudsurShopBundle:Default:productOverview.html.twig', array(
                'group' => $group
            )
        );

    }

}

src/Audsur/ShopBundle/Entity/Category.php

<?php

namespace AudsurShopBundleEntity;

use DoctrineORMMapping as ORM;
use DoctrineCommonCollectionsArrayCollection;

/**
 * @ORMEntity
 * @ORMTable(name="category")
 */
class Category
{
    /**
     * @ORMColumn(type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORMColumn(type="string", length=100, unique=true)
     */
    protected $name;

    /**
     * @ORMColumn(type="string", length=255, nullable=false, unique=true)
     */
    protected $slug;

    /**
     * @ORMColumn(type="text")
     */
    protected $description;

    /**
     * @ORMOneToMany(targetEntity="Product", mappedBy="category")
     */
    protected $products;

    public function __construct()
    {
        $this->products = new ArrayCollection();
    }


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Category
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set slug
     *
     * @param string $slug
     * @return Category
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

    /**
     * Get slug
     *
     * @return string 
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Category
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Add products
     *
     * @param AudsurShopBundleEntityProduct $products
     * @return Category
     */
    public function addProduct(AudsurShopBundleEntityProduct $products)
    {
        $this->products[] = $products;

        return $this;
    }

    /**
     * Remove products
     *
     * @param AudsurShopBundleEntityProduct $products
     */
    public function removeProduct(AudsurShopBundleEntityProduct $products)
    {
        $this->products->removeElement($products);
    }

    /**
     * Get products
     *
     * @return DoctrineCommonCollectionsCollection 
     */
    public function getProducts()
    {
        return $this->products;
    }
}

Ответ, как всегда, оказался проще простого.
Создаём в модели геттер

public function getAssociatedArray()
{
    return $this->getAssociatedProducts()->select('id')->column();
}

На выходе получаем массив с нужными id, все категории, которые привязаны к продукту, ну или наоборот, все категории, к которым привязан продукт.
Теперь в форме этот геттер можно использовать так:

<?= $form->field($model, 'associatedArray')->dropDownList(Catalog::getChildCategoryList(),
            [
                'multiple' => true,
                'class' => 'select-multiple',
                'style' => 'width:100%;',
            ])
        ?>

При создании новой записи мы получим все категории, из которых можно выбрать несколько для продукта.
При обновлении записи мы получим все категории, к которым привязан продукт.

p.s. Это только малая часть кода, которая не даёт возникать ошибке

Call to a member function isAttributeRequired() on array

Для того, чтобы сохранить данные в базе — надо расширять данный код, дописывать функционал.

p.s.s Ответ подсмотрел у одного хорошего человека)))

Here it is

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.3.*",
        "jenssegers/mongodb": "^3.0",
        "guzzlehttp/guzzle": "^6.2",
        "predis/predis": "^1.1",
        "symfony/finder": "^3.1",
        "symfony/event-dispatcher": "2.8.9",
        "rocket-code/shopify": "^2.0"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.0",
        "symfony/css-selector": "3.1.*",
        "symfony/dom-crawler": "3.1.*",
        "laravel/homestead": "^3.0",
        "squizlabs/php_codesniffer": "^2.6"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-root-package-install": [
            "php -r "file_exists('.env') || copy('.env.example', '.env');""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\Foundation\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\Foundation\ComposerScripts::postUpdate",
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

I’m having the weirdest error.

When trying to display a custom loop, I get the following error:

Fatal error
: Uncaught Error: Call to a member function have_posts() on array in /.../custom-page.php:42 Stack trace: #0 /.../wp-includes/template-loader.php(106): include() #1 /.../wp-blog-header.php(19): require_once('/data/sites/web...') #2 /.../index.php(17): require('/data/sites/web...') #3 {main} thrown in
/.../custom-page.php
on line
42

Which is so weird, because I’ve seen the error with ‘call to a member function on null’ or something else, but not on array, which is usually fine for this function.

The content of my custom-page.php has something like this:

<?php get_header(); ?>

<div class="container">
    <div class="row">
        <div class="col-12">
            <h1><?php the_title(); ?></h1>
            
            <div class="grid row">
                
                <?php foreach( $programs as $program ) {
                    
                    $custom_query = get_posts( [
                        'post_type'=> 'artikel',
                        'post_status' => 'publish',
                        'posts_per_page' => 1,
                        'order' => 'DESC',
                        'orderby' => 'date',
                        'meta_query' => [
                            [ 'key' => 'layout', 'value' => 'synopsis' ],
                            [ 'key' => 'programs', 'value' => '"' . $program . '"', 'compare' => 'LIKE' ]
                            ]
                        ] );
                    
                    if( $custom_query->have_posts() ) {
                        
                        echo 'test';
                        
                    }
                    
                } ?>
                
            </div>
            
        </div>
    </div>
</div>

<?php get_footer(); ?>

Answer by Rafael Park

Q. Why return this message -> Call to a member function save() on array laravel
Ans : First of all you check $id value has or not into the table.,Im doing the update method. When I tried to update the specific data, im getting this error «Call to a member function save() on array». Why? Is there’s something missing in my codes?,

What do you call the floor-level space that allows someone to traverse from one floor to another with stairs?

,

Stack Overflow for Teams
Where developers & technologists share private knowledge with coworkers

public function updateText(Request $request, $id)
{
    $result = YourModel::find($id);
    $result->your_column_1 = $request->your_value_1;
    $result->your_column_2 = $request->your_value_2;
    $result->your_column_3 = $request->your_value_3;
    $result->your_column_4 = $request->your_value_4;
    .
    .
    .
    $result->your_column_n = $request->your_value_n;

    if($result->save()){
        Session::flash('flash_message', 'Task successfully added!');
    }else{
        Session::flash('flash_message', 'Task failed!');
    }

    return redirect()->back();
}

Answer by Zahra Bowen

Hey so I’m trying to change data and update them. But this error shows up when I press update button: «Call to a member function save() on array»
So this is my code:,
VueJS show different auth-navigation for tenancy,
laravel 8: BadMethodCallException Method AppHttpControllersUsersGestionController::show does not exist,
Jquery Validation GreaterThanEqual & LessThanEqual not working correctly above number 9

Controller:

public function update(Request $r)
{
     
    $update_id = $r->uid;

    $name = $r->uname;
    $email = $r->umail;
    $add = $r->uadd;

    $update =  AppModelsEmp_model::find($update_id);

    $update['name']=$name;
    $update['email']=$email;
    $update['address']=$add;

    $updated=$update->save();

    if ($updated) {
        return redirect('show')->with('message', 'Data added successfully!');
    }
    
}

Routes:

Route::get('/show', [Employee::class, 'fetch']);
Route::post('/update_data', [Employee::class, 'update']);

Action:

<form action="{{ url('/update_data') }}" method="post">

Answer by Lucy Hayden

Call to a member function save() on null,Hello guys I’m using laravel 5 polymorphic relation to save the data in the database but I’m facing some problem. When ever I try to save the data in the database it is throwing me this error ,I ‘m making a polymorphic relation like this. A post and comment can have many likes. ,I don’t know why I’m facing this error. I’m following this tutorial fot the polymorphic relation Creating Polymorphic Relations in Laravel 5.

Like Controller

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppHttpRequests;
use AppHttpRequestsLikeRequest;
use AppCommandsLikeCommand;
// use AppCommandsReadLikeCommand;
use AppHttpControllersController;



use IlluminateBusDispatcher;
// use AppTransformersPostTransformer;
use Exception;
// use AppEventsTestEvent;
use AppExceptionsCustomNotPermissionException;
use AppExceptionsCustomNameNotFound;
class LikeController extends Controller
{

    public function likeComment(LikeRequest $data){
        try{
            $render = $this->dispatch(new LikeCommand("comment" , $data));
        }catch(Exception $e){
            $e->getMessage();
        }
    }

    public function likePost(LikeRequest $data){
        error_log("1");
        try{
            $render = $this->dispatch(new LikeCommand("post" , $data));
        }catch(Exception $e){
            error_log("error : ".$e->getMessage());
        }
    }
}

Like Command

<?php

namespace AppCommands;

use AppCommandsCommand;
use IlluminateContractsBusSelfHandling;
use IlluminateFoundationBusDispatchesJobs;
use AppRepositoriesLikeRepository;
use Exception;
use DB;
use AppLikeModel;
use Artisan;


use AppRepositoriesPostRepository;

class LikeCommand extends Command implements SelfHandling
{

    use DispatchesJobs;


    private $postId;
    private $action;
    private $data;




    /**
     * Create a new command instance.
     *
     * @param $request
     *
     * @internal param $email
     * @internal param $phone
     * @internal param $comments
     * @internal param $name
     */

    public function __construct($action,$request)
    {
        $this->action = $action;
        $this->postId = $request->id;
        $this->data = $request;
        error_log("Hello in the construct");
    }

    /**
     * Execute the command.
     *
     * @param TestRepository $TestRepository
     */
    public function handle(LikeRepository $LikeRepo, PostRepository $postRepo )
    {  

        error_log("Hello");
        error_log("A : ".$this->action );
        error_log("ID : ".$this->postId);

        if($this->action =="comment"){
            error_log("in like comment");
          return  $LikeRepo->LikeComment( $this->postId);
        }else if ($this->action == "post"){ 
            error_log("2");
           return $LikeRepo->LikePost( $this->postId, $postRepo , );
        }


    }
}

Like Repo

<?php

namespace AppRepositories;

use AppRepositoriesCommentRepository;
use AppRepositoriesPostRepository;
use AppCommentModel;
use AppLikeModel;
class LikeRepository
{
    public function create($comment)
    {
        // error_log("Trying to save now. Let's see");
         $Like = new LikeModel;
        $Like->post_id = $comment;
        // $Comment->post_id = $this->post_id;
        $comment->save();

    }   
    public function LikeComment($id) {
        // return CommentModel::where('post_id' , $id)->get();
        // return CommentModel::get();
    }

    public function LikePost($id, PostRepository $postRepo){
        error_log("3");
        $result = $postRepo->getById($id);
        error_log("4");


        // $Like = DB::transaction(function () use ($LikeRepository) {
        $Like = new likeModel;
        error_log("5");
        $result->Like->save($like);
        error_log("6");
        $Like->status="success";
        // });
        return $Like;
    }
}

Like Model

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class LikeModel extends Model
{
    public $table = "likes";
    //
    public function likeable()
    {
      return $this->morphTo();
    }
}

Post Model

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class PostModel extends Model
{

    //
    public $table = "posts";

    public function likes()
    {
      return $this->morphMany('AppLike', 'likeable');
    }
}

Comment Model

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class CommentModel extends Model
{
    //
    public $table = "comments";

    public function likes()
    {
      return $this->morphMany('AppLike', 'likeable');
    }
}

Answer by Annabelle Little

You need to set the attributes on your Qualification model either individually, or all at once and then call save().,Error: Call to a member function update() on array laravel ,I am getting this error «Call to a member function update() on array» and I have no idea why, is it because I am updating an array? I have check other resources similar to this but not much related to array so I am not sure what to do. Thank you in advance,

Rakesh

3 Years ago

You need to set the attributes on your Qualification model either individually, or all at once and then call save().
public function update1(Request $request, $id){
$object2 = qualification::find($id);
$test = array();
$test[‘School’] = implode(‘ , ‘, $request->School);
$test[‘SDate’] = implode(‘ , ‘, $request->SDate);
$test[‘EDate’] = implode(‘ , ‘, $request->EDate);
$test[‘qualification’] = implode(‘ , ‘, $request->qualification);
$object2->update($test);
return redirect(‘/home’);
}

Controller:

public function update1(Request $request, $id){
    $object2 = qualification::find($id);
    $object2 = array();
$object2['School'] = implode(' , ', $request->School);
$object2['SDate'] = implode(' , ', $request->SDate);
$object2['EDate'] = implode(' , ', $request->EDate);
$object2['qualification'] = implode(' , ', $request->qualification);
 $object2->update();
    return redirect('/home');
}

qualification model:

class qualification extends Eloquent
{
    protected $fillable = array('School', 'user_id', 'SDate', 'EDate', 'qualification');

    // DEFINE RELATIONSHIPS --------------------------------------------------
    public function personal_infos() {
        return $this->belongsTo('Apppersonal_info');
    }
}

Answer by Reese Harvey

BelongsToSelect: Call to a member function save() on string
,When calling $this->form->getState() then BelongsToSelect line 108 throws an error, due to $this->getModel() returns a string and not the model class.,Now, you should call saveRelationships() once you have a model to associate with:,I’ve just released a small fix in beta25.

The model:

class Department extends Model
{
    protected $fillable = [
        'title',
        'parent_id'
    ];

    public function owner(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}

Livewire component

protected function getFormSchema(): array
{
    return [
        TextInput::make('title')->required()->unique(Department::class),
        BelongsToSelect::make('owner')->relationship('owner', 'name')
    ];
}

protected function getFormModel(): string
{
    return Department::class;
}

public function create(): void
{
    Department::create($this->form->getState());
}

Answer by Madden Mathis

The class JenssegersMongodbQueryBuilder check in the constructor if it should use collections or not.,where $query is an instance of JensSegersMongodbEloquentBuilder.,@jversmis thanks for your input. would you mind telling me the right position to input the app() function. I am getting an syntax error when I included app function about shouldUseCollections.,The error is thrown in IlluminateDatabaseEloquentBuilder->getModels()
This function is called by

use JenssegersMongodbEloquentModel as Moloquent;
class Product extends Moloquent
{
    protected $connection="mongodb";
    protected $dates = [
        'created_at', 'last_modified'
    ];
    protected $collection="products";
}

Возможно, вам также будет интересно:

  • Ошибка call of duty modern warfare онлайн
  • Ошибка call of duty modern warfare fatal error
  • Ошибка c50 сузуки бургман 650
  • Ошибка call of duty ghost иероглифы
  • Ошибка c5 1710 принтер hp

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии