Laravel - Object of class stdClass could not be converted to int - php

i have a small search for my cars table. It all works fine until I add this to my view:
#guest
<i class="icon-heart"></i>
#else
#if(auth()->user()->hasLiked($car))
<span class="auto-featured"><a id="like{{$car->id}}-bs3" style="cursor: pointer;"><i
id="like{{$car->id}}" class="icon-heart" style="color:white"></i></a>
{{$car->likers()->count()}}</span>
#else
<span class="auto-featured"><a id="like{{$car->id}}-bs3" style="cursor: pointer;"><i
id="like{{$car->id}}" class="icon-heart-o" style="color:white;font-family: 'Raleway', sans-serif;">
</i></a> {{$car->likers()->count()}}</span>
#endif
#endguest
After that it shows me this error: Object of class stdClass could not be converted to int. I'm using overtrue for like, follow and more.
This is my search() function:
public function search(Request $request){
$carQuery = DB::table('cars');
$cars = Car::all();
//$cars = Car::orderBy('placeni_status', 'desc')->get();
// standard where fields
foreach ($request->only(['marka', 'model']) as $term => $value) {
if (empty($value)) {
continue;
}
$carQuery->where($term, $value);
}
// gear is one of gears array values
if ($sigurnost = $request->get('sigurnost')) {
$carQuery->whereIn('sigurnost', $sigurnost);
}
// gear is one of gears array values
if ($karoserija = $request->get('karoserija')) {
$carQuery->where('karoserija', $karoserija);
}
// gear is one of gears array values
if ($gorivo = $request->get('gorivo')) {
$carQuery->where('gorivo', $gorivo);
}
if($lokacija = $request->get('lokacija')){
$carQuery->where($cars->user->city, $lokacija);
}
// between a price from/to the values set
if (
$from = $request->input('from')
&& $to = $request->input('to')
) {
$carQuery->whereBetween('cijena', [$from, $to]);
}
// between a price from/to the values set
if (
$fromm = $request->input('fromm')
&& $too = $request->input('too')
) {
$carQuery->whereBetween('kilometraza', [$fromm, $too]);
}
if (
$od = $request->input('od')
&& $do = $request->input('do')
) {
$carQuery->whereBetween('godiste', [$od, $do]);
}
$cars = $carQuery->orderBy('placeni_status', 'desc')->get();
return view('search.cars')->with('cars', $cars);
}
What I'm doing wrong and what this error mean? I just need to show on searched cars number of likes and some other stuff like favorite and follow.
This is my ajaxRequest from CarsController:
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function ajaxRequestCars(Request $request){
$car = Car::find($request->id);
$response = auth()->user()->toggleLike($car);
//$response = auth()->user()->toggleFavorite($car);
return response()->json(['success'=>$response]);
}
And this is my Car.php model:
<?php
namespace App;
use Overtrue\LaravelFollow\Traits\CanBeLiked;
use Overtrue\LaravelFollow\Traits\CanBeBookmarked;
use Overtrue\LaravelFollow\Traits\CanBeFavorited;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Car extends Model
{
use CanBeLiked, CanBeBookmarked, CanBeFavorited, CanBeFollowed;
protected $table = "cars";
protected $primaryKey = "id";
protected $fillable = [
'naslov', 'marka', 'model', 'kubikaza', 'zamajac', 'karoserija', 'godiste', 'kilometraza', 'br_brzina_mjenjaca',
'gorivo', 'vlasnistvo', 'kilovata', 'konjska_snaga', 'emisiona_klasa', 'pogon', 'mjenjac', 'br_vrata', 'velicina_felni', 'posjeduje_gume',
'br_sjedista', 'str_volana', 'klima', 'boja_spolj', 'boja_unutrasnj', 'materijal_unutrasnj', 'registracija', 'ostecenje',
'zamjena', 'sigurnost', 'oprema', 'stanje', 'nacin_finansiranja', 'nacin_prodaje', 'cijena', 'vrsta_cijene', 'opis_oglasa', 'fotografije'
];
public function user(){
return $this->belongsTo(User::class);
}
public function vehicleinfo(){
return $this->hasMany(VehicleInfo::class);
}
public function ad(){
return $this->hasMany(Ad::class);
}
}

I suppose the $car->likers() returns the relationship instance, not the actual likers. Try doing $car->likers->count() on both places.

Related

Laravel Model is freezing the server. Timeout error

I'm having a really strange issue here. I have a user model (detailed below).
It all works fine until I added the getReportsSharedAttribute function. When this is added, the server freezes and I get:
PHP Fatal error: Maximum execution time of 60 seconds exceeded in C:\Users\User\PhpstormProjects\laravel-vue\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasRelationships.php on line 637
more:
exception: "Symfony\\Component\\ErrorHandler\\Error\\FatalError"
file: "C:\\Users\\User\\PhpstormProjects\\laravel-vue\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php"
I thought there was something up with the code, so I ran it manually in a controller and dumped it, it worked fine.
So I tried it as a relation instead of an attribute. Same error.
So then I thought, is it just specific to the ReportingSetAssigned model, so I did another query on another collection, and another, and I still get the timeout error.
I tried another Model, it worked fine, for no apparent reason. Even though there were a lot more records inside. It doesn't seem to be dependant on how many columns are involved in the return. None of my tables have more than 50 records inside, even in the relations.
What's going on here? Is there some limit somewhere?
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Query\Builder;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\HasApiTokens;
use stdClass;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, SoftDeletes;
public $appends = [
'full_name',
'profile_photo_thumb',
'permissions_alt',
'line_managed_only_id',
'line_managers_only_id',
'permissions_meetings_only_id',
'reports_shared',
];
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $dates = ['deleted_at'];
public function permissions(){
return $this->belongsToMany(Permission::class);
}
public function timelineitems(){
return $this->hasMany(TimelineItem::class);
}
public function line_managers(){
return $this->belongsToMany(User::class,'permissions_lm','user_id','lm_id');
}
public function line_managed(){
return $this->belongsToMany(User::class,'permissions_lm','lm_id','user_id');
}
public function permissions_meetings(){
return $this->belongsToMany(Area::class,'permissions_meetings','user_id','area_id')->withPivot('level');
}
public function getPermissionsMeetingsOnlyIdAttribute(){
return $this->permissions_meetings()->pluck('permissions_meetings.area_id');
}
public function permissions_qed(){
return $this->belongsToMany(Area::class,'permissions_qed','user_id','area_id')->withPivot('level');
}
public function permissions_reporting(){
return $this->belongsToMany(Area::class,'permissions_reporting','user_id','area_id')->withPivot('level');
}
public function permissions_reporting_sets(){
return $this->belongsToMany(ReportingSet::class,'permissions_reporting_sets','user_id','set_id')->withPivot('level');
}
public function improvement_category_objective_action_milestones(){
return $this->belongsToMany(ImprovementSetCategoryObjectiveActionMilestone::class);
}
public function planning_review_forms(){
return $this->hasMany(PerformanceManagementSetAssigned::class)->whereHas('set', function($q) {
$q->where('appraisal', 0);
});
}
public function appraisal_forms(){
return $this->hasMany(PerformanceManagementSetAssigned::class)->whereHas('set', function($q) {
$q->where('appraisal', 1);
});
}
public function performance_manager_set_as_lm(){
return $this->belongsTo(PerformanceManagementSetAssigned::class, 'lm_id');
}
public function getPermissionsAttribute(){
return $this->permissions()->get();
}
public function getLineManagersOnlyIdAttribute(){
return $this->line_managers()->pluck('permissions_lm.lm_id');
}
public function getLineManagedOnlyIdAttribute(){
return $this->line_managed()->pluck('permissions_lm.user_id');
}
public function hasPermissionTo($permission){
if(auth()->user()->super_admin){
return true;
}
if($permission==='super_admin'&&auth()->user()->super_admin){
return true;
}
if(!is_array($permission)){
$access = $this->permissions()->where('permission', $permission)->exists();
if($access){
return true;
}
return false;
}else{
foreach($permission as $p){
$access = $this->permissions()->where('permission', $permission)->exists();
if($access){
return true;
}
}
}
}
public function checkPermissionReportingSet($permission){
$access = $this->permissions_reporting_sets()->where('set_id', $permission)->first();
if($access){
if($access->pivot->level=='read'){
return 'read';
}
if($access->pivot->level=='write'){
return 'write';
}
}
}
public function checkPermissionReportingArea($permission){
$access = $this->permissions_reporting()->where('area_id', $permission)->first();
if($access){
if($access->pivot->level=='true'){
return true;
}
}
}
public function truePermission($permission){
$access = $this->permissions()->where('permission', $permission)->exists();
if($access){
return true;
}
}
public function updateTimeline($type_main,$type_sub,$title,$content,$icon,$color,$link,$relevant_id = null,$user_id = null){
if(!$user_id){
$user_id = $this->id;
}
$t = new TimelineItem();
$t->type_main = $type_main;
$t->type_sub = $type_sub;
$t->title = $title;
$t->content = $content;
$t->icon = $icon;
$t->color = $color;
$t->link = $link;
$t->user_id = $user_id;
$t->relevant_id = $relevant_id;
$t->save();
}
public function getPermissionsForVueAttribute(){
$permissions = $this->permissions;
$new = [];
foreach($permissions as $p){
$new[$p->permission] = true;
}
$new['meeting_areas'] = [];
$permissions = $this->permissions_meetings;
foreach($permissions as $p){
$new['meeting_areas'][$p->id] = $p->pivot->level;
}
$new['qed_areas'] = [];
$permissions = $this->permissions_qed;
foreach($permissions as $p){
$new['qed_areas'][$p->id] = $p->pivot->level;
}
$new['reporting_areas'] = [];
$permissions = $this->permissions_reporting;
foreach($permissions as $p){
$new['reporting_areas'][$p->id] = $p->pivot->level;
}
$new['reporting_sets'] = [];
$permissions = $this->permissions_reporting_sets;
foreach($permissions as $p){
$new['reporting_sets'][$p->id] = $p->pivot->level;
}
return json_encode($new);
}
public function getPermissionsAltAttribute(){
//General permissions
$permissions = Permission::get();
$newP = [];
foreach($permissions as $p){
$newP[$p->permission] = false;
}
$permissions = $this->permissions;
foreach($permissions as $p){
$newP[$p->permission] = true;
}
$newP['meeting_areas'] = [];
$newP['qed_areas'] = [];
$newP['reporting_areas'] = [];
$newP['reporting_sets'] = [];
foreach(Area::orderBy('name', 'ASC')->get() as $p){
$newP['meeting_areas'][$p->id] = "false";
$newP['qed_areas'][$p->id] = "false";
$newP['reporting_areas'][$p->id] = "false";
}
$meetings = DB::table('permissions_meetings')->where('user_id', '=', $this->id)->get();
foreach($meetings as $p){
$newP['meeting_areas'][$p->area_id] = $p->level;
}
$qed = DB::table('permissions_qed')->where('user_id', '=', $this->id)->get();
foreach($qed as $p){
$newP['qed_areas'][$p->area_id] = $p->level;
}
$reporting = DB::table('permissions_reporting')->where('user_id', '=', $this->id)->get();
foreach($reporting as $p){
$newP['reporting_areas'][$p->area_id] = $p->level;
}
foreach(ReportingSet::orderBy('name', 'ASC')->get() as $p){
$newP['reporting_sets'][$p->id] = "false";
}
$reporting = DB::table('permissions_reporting_sets')->where('user_id', '=', $this->id)->get();
foreach($reporting as $p){
$newP['reporting_sets'][$p->set_id] = $p->level;
}
return $newP;
}
public function getCyclesAttribute(){
return Cycle::orderBy('id')->get();
}
public function getFullNameAttribute(){
return $this->first_name . " " . $this->last_name;
}
public function getProfilePhotoThumbAttribute(){
if($this->profile_photo){ return "THUMB-" . $this->profile_photo; }else{ return "no-avatar.png"; }
}
public function getReportsSharedAttribute(){
return ReportingSet::where('observee_id', $this->id)->where('observee_share', 1)->where('published', 1)->without('set.modules')->get()->toArray();
}
public function canLineManage($id){
if($this->super_admin==1) return true;
foreach($this->line_managed as $lm){
if($lm->id==$id){
return true;
}
}
}
}
EDIT: If I run this code in a controller, it does't hang at all. It loads up the data in less than a second
EDIT: Restarted computer, still happening
This looks a lot like an infinitive call-loop, please refer to this on github issue
Allowed Memory size exhaused when accessing undefined index in toArray
You are just running out of memory when calling parent::toArray(). You
either need to reduce the amount of items in your collection or
increase your allowed memory allocation.

laravel eloquent foreach loop error Trying to get property 'location_id' of non-object

This one has happened to me before but I have no idea why and how to avoid it. So I have a static function in a Model which gets all the database rows and uses a foreach loop to read another table but I am unable to correctly read the row data:
public static function test()
{
$accounts = self::where( 'is_enabled', 1 )->get();
foreach ( $accounts as $account ) {
$map = AccountMap::where( 'account_id', $account->id )->first();
$location = Location::getLocation( $map->location_id );
$data = $location->getData();
}
}
So the above function gathers an array of items ($accounts) this is then passed into a foreach loop all is fine to this point but if i now use $account->id it is null. The id is shown in the Account object in its attributes folder.
A very similar function is used elsewhere in this model but it uses a passed id and this one works (however $account->id is null). The issue is not the database or column names:
public static function getThisLocation( $id )
{
$account = self::find( $id );
$map = AccountMap::where( 'account_id', $id )->first();
location = Location::getLocation( $map->location_id );
$data = $location->getData();
return $data;
}
*** EDIT ***
Account, AccountMap and Location are all Eloquent models
namespace App\Models;
use Eloquent;
use App\Notifications\AccountMessages;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Notifications\Notifiable;
/**
* #method static find(int $id)
*/
class Account extends Eloquent
{
use Sortable;
use Notifiable;
public $sortable = [
'id',
'name',
'lastupdate',
'url'
];
public static function test()
{
$accounts = self::where( 'is_enabled', 1 )->get();
foreach ( $accounts as $account ) {
$map = AccountMap::where( 'account_id', $account->id )->first();
$location = Location::getLocation( $map->location_id );
$data = $location->getData();
}
}
public static function getThisLocation( $id )
{
$account = self::find( $id );
$map = AccountMap::where( 'account_id', $id )->first();
location = Location::getLocation( $map->location_id );
$data = $location->getData();
return $data;
}
}
namespace App\Models;
use Eloquent;
use Kyslik\ColumnSortable\Sortable;
/**
* #method static where(string $string, int $id)
*/
class AccountMap extends Eloquent
{
use Sortable;
public $sortable = [
'id',
'account_id',
'location'
];
}
*** MORE EDIT ***
I have confirmed that using $account->attributes['id'] has worked but I've no idea why what I expected to work didn't ($account->id)
The problem must be something related to communication of your model and migration.
Add this dd() to your current test function:
public static function test()
{
$accounts = self::where( 'is_enabled', 1 )->get();
foreach ( $accounts as $account ) {
if ($account->id){
$map = AccountMap::where( 'account_id', $account->id )->first();
$location = Location::getLocation( $map->location_id );
$data = $location->getData();
} else {
dd($account)
}
}
}
Then Check the result and see is there the id filed on your response? If not, The id field doesn't exist on your self Model and it's Your problem's cause.
Finally, Check your model fields easily with :
public function testReturnOfSelfModel()
{
$data= self::all();
dd($data);
}
If you have id on this dd function, Your Model working properly. If not, you dont have id field.
Also, it is more professional to change Capitalize your model's first charachter. It sholud be Self, not self.
I'd suggest to setup two proper data Model (a migration would need to create these tables):
class Account extends Model {
protected $table = 'accounts';
public $timestamps = false;
/**
* The attributes that are mass assignable.
* #var array
*/
protected $fillable = [];
/**
* The attributes that should be hidden for arrays.
* #var array
*/
protected $hidden = [];
}
Unless defining protected $table it will definitely not know what to do.
It's rather unclear what you're even trying to accomplish with AcountMap, but it may need a relation defined; which eg. with return $this->belongsTo(Account::class); ...while simply adding lat & lng to class Account would be far less complex and perfectly fine, while it's only 1 location.

How can I retrieve only filtered records in a Child Model?

I have a table that I want to use to show records of timesheet logs, I've been able to do a filter using whereHas which works, but when I try to filter by employee I still get the logs for all employees attribtued to those jobs instead of the one I'm searching for.
My controller:
$request = json_decode(json_encode($request->all(), true))->params;
$jobs = Job::whereHas('timesheets', function($query) use ($request) {
if (count($request->selected_employees) > 0) {
$query->wherein('employee_id', $request->selected_employees);
}
if (count($request->selected_clients) > 0) {
$query->wherein('client_id', $request->selected_clients);
}
if (!empty($request->start_date)) {
$query->where('date','>=',$request->start_date);
}
if (!empty($request->end_date)) {
$query->where('date','<=',$request->end_date);
}
});
$jobs = (new Job)->generateReport($jobs->get(), $request->selected_employees);
$result = array_merge_recursive($jobs);
return $result;
My Model which iterates through the job. So far everything is accurate except for the child relationship called 'timesheets', it's not defined here, but laravel auto populates it and I am not able to overwrite/replace anything with that attribute. Any ideas?
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Job extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ["client_id", "job_number", "job_date", "payment_type", "rate", "description"];
public $totalHoursArray = array();
/**
* #var array|mixed
*/
private $report_totals;
public function client() {
return $this->belongsTo(Client::class);
}
public function timesheets() {
return $this->hasMany(TimesheetLog::class);
}
public function creator(){
return $this->belongsTo(User::class,'created_by');
}
public function editor(){
return $this->belongsTo(User::class,'edited_by');
}
/**
*
* Returns a count of Employee Hours per job for timesheet entries
* currently selected in the Job model
*
* #return array
*/
public function getEmployeeHoursPerJob($employee_ids){
$i = 0;
$hours_per_job = array();
$timesheets = empty($employee_ids) ? $this->timesheets : $this->timesheets->whereIn('employee_id',$employee_ids);
foreach ( $timesheets as $trow) {
$trow->employee_code = Employee::find($trow->employee_id)->code;
$date = new \DateTime($trow->date);
$trow->date = date_format($date, 'd-m-Y');
//find if the employee exists in the hours per job array if not, push a new row
$found = array_search($trow->employee_id,array_column($hours_per_job, 'employee_id', isset($hours_per_job['employee_id']) ? 'employee_id' : null));
if($i > 0 && $found !== false){
$hours_per_job[$found]['total_time'] += $trow->total_time;
} else {
array_push($hours_per_job, ['employee_id' => $trow->employee_id, 'employee_code' => $trow->employee_code, 'total_time' => ($trow->total_time)]);
}
$i++;
}
return $hours_per_job;
}
public function generateReport($jobs, Array $employee_ids){
$report_totals = array();
$filtered_timesheets = array();
foreach ($jobs AS $jobrow) {
$i = 0;
$jobrow->client_name = Client::find($jobrow->client_id)->name;
$jobrow->attention = Client::find($jobrow->client_id)->attention;
$jobrow->rate = "$".$jobrow->rate ." ". $jobrow->payment_type;
$dateT = new \DateTime($jobrow->job_date);
$jobrow->job_date = date_format($dateT, 'd-m-Y');
$hours = $jobrow->getEmployeeHoursPerJob($employee_ids);
$jobrow->employee_hours = $hours;
foreach ($filtered_timesheets as $timesheetf){
array_push($timesheets_filtered, $timesheetf);
}
foreach($hours AS $hoursRow){
$found = array_search($hoursRow['employee_id'],array_column($report_totals, 'employee_id',
isset($report_totals['employee_id']) ? 'employee_id' : null));
if($found !== false){
$report_totals[$found]['total_time'] += $hoursRow['total_time'];
} else {
array_push($report_totals, $hoursRow);
$i++;
}
}
}
return compact('jobs','report_totals');
}
}
In the foreach loop I assigned a new property of the row to a wherein query and this was accurate and what I wanted. But again, I couldn't replace or assign the original property that I want to send to the view.
$jobrow->timesheets_filtered = $jobrow->timesheets->wherein('employee_id',$employee_ids)->toArray();

Laravel not getting Accessor Trying to get property on a non-object

I'm trying to get the value of a map object to check if a user made a rating or not.
{{ $book->rated }} is returning neither false or true.
in tinker
$book->getTypeAttribute(); PHP Notice: Trying to get property of
non-object in /Applications/MAMP/htdocs/elirating/app/Book.php on line
40
This method needs to get the type of the rating, the default value is set to false
public function getTypeAttribute(){
return Rate::where('type', $this->attributes['id'])->where('user_id',auth()->user()->id) === self::RATED;
}
Book.php
use Illuminate\Database\Eloquent\Model;
use willvincent\Rateable\Rateable;
use App\User;
use App\Rate;
class Book extends Model
{
use Rateable;
const RATED = "true";
const NOT_RATED = "false";
protected $fillable = [ 'user_id', 'title', 'description'];
public function scopeGetBook($query, $book_name )
{
return $query->where('slug', $book_name );
}
public function setTitleAttribute($value)
{
$this->attributes['title'] = $value;
$this->attributes['slug'] = str_slug($value);
}
public function scopeGetBookUser($query, $user_id)
{
return $query->where('user_id', $user_id )->first();
}
public function getTypeAttribute(){
return Rate::where('type', $this->attributes['id'])->where('user_id',Auth()->user()->id) === self::RATED;
}
Rate.php
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
use willvincent\Rateable\Rateable;
class Rate extends Model
{
protected $fillable = [
'user_id',
'type',
'rating'
];
public $timestamps = false;
protected $table = 'ratings';
}
BookController.php (this is how the type is being set, and how im trying to retrieve the value)
public function rate(Request $request, $book_id)
{
$book = Book::find($book_id);
$rating = $book->ratings()->where('user_id', auth()->user()->id)->first();
if(is_null($rating)){
$ratings = new Rating();
$ratings->rating = $request['rating'];
$ratings->user_id = auth()->user()->id;
$ratings->type = Book::RATED;
$book->ratings()->save($ratings);
return json_encode($book);
}
else{
return response()->json(['status' => 'You already left a review']);
}
}
public function show($book_name)
{
$books = Book::with('ratings')->GetBook($book_name)->get();
$data = $books->map(function(Book $book){
$book['rated'] = $book->getTypeAttribute();
return $book;
});
return view('books.show', compact('data', $data));
}
HTML
<div id="rateYo" data-rateyo-rating="{{ $book->userSumRating or 0}}" data-rateyo-read-only="{{ $book->rated }}" > ></div>
image(the read-only attribute needs to have either true of false) it doesn't show neither.
You need to call first or get on the query in the accessor:
return Rate::where(['type' => $this->getKey(), 'user_id' => auth()->id()])->first()
Also, when using accessors, you don't call the full function, as in getTypeAttribute, you only use the attribute name, type.
// wrong
$book['rated'] = $book->getTypeAttribute();
// right
$book['rated'] = $book->type;
However, I think what you should be doing to find if a user has left a rating is to use the exists or doesntExist query functions. For example:
// this will return true/false
public function getRatedAttribute()
{
return Rate::where(['type' => $this->getKey(), 'user_id' => auth()->id()])->exists();
}
Append the attribute to the Book model:
// this will add the attribute to each book in the query result.
protected $appends = ['rated']; // or type
Then you can simply use:
$book->rated; // true if a rating exists, otherwise false.

Laravel from for each to array how?

this is the result of a Foreach loop get method using dd$($value),
Questions: how do i convert this inside my controller into an array and store it into my database
Example: [Lead_id1=Subjectid1 , Lead_id2=Subjectid1, Lead_id3=Subjectid1]
so on and so fort..
Note: Lead_id and Subject_id are both FK there for the value must be integer Not String
Controller:
public function store(Request $request)
{
$value=$request->all();
$subjects = $value['Subject_id'] ?? [];
$leads = $value['Lead_id'] ?? [];
$data = [];
foreach ($subjects as $subject) {
$data[] = array_combine($leads, array_fill(0, count($leads), $subject));
$scores=new Score;
$scores->Subject_id=$request->input('Subject_id');
$scores->Lead_id=$request->input('Lead_id');
dd($scores);
$scores->save();
}
this is the result
Score Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Score extends Model
{
protected $guarded = [
'id',
'Year_id',
'Term_id',
'Level_id',
'Classes_id',
'Subject_id',
'Lead_id',
];
}
You said Lead_id and Subject_id both are foreign key then you can simply use ManyToMany relation in laravel and save the data accordingly
Subject Model
class Subject extends Model{
public function leads(){
return $this->belongsToMany(Lead::class, 'scores', 'Subject_id', 'Lead_id');
}
}
Lead Model
class Lead extends Model{
public function subjects(){
return $this->belongsToMany(Subject::class, 'scores', 'Lead_id', 'Subject_id');
}
}
Questions: how do i convert this inside my controller into an array and store it into my database
foreach($data['Subject_id'] as $subjectId){
$subject = Subject::find($subjectId);
$leadids = $data['Lead_id'];
$subject->leads()->attach($leadids);
}
For details check this https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
You can try -
$temp = [];
$subject = !empty($value['Subject_id'][0]) ? $value['Subject_id'][0] : null; // extract the subject id
// Loop through lead ids
foreach($value['Lead_id'] as $lead) {
$temp[$lead] = $subject; // store subject id fro lead ids
}
You may try following :
public function store(Request $request)
{
$value=$request->all();
$subjects = $value['Subject_id'] ?? [];
$leads = $value['Lead_id'] ?? [];
$data = [];
foreach ($subjects as $subject) {
$data[] = array_combine($leads, array_fill(0, count($leads), $subject));
}
foreach ($data as $load => $subject) {
$scores = new Score;
$scores->Subject_id = $subject;
$scores->Lead_id = $load;
$scores->save();
dd($scores);
}
}
convert the array first into a json string
json_encode($array);
before store it to the database

Categories