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
Related
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.
Assuming the Model Order
class Order extends Model {
use HasFactory;
protected $table = 'order';
protected $primaryKey = 'id';
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
public function extra(){
return $this->hasOne(Extra::class);
}
public function products(){
return $this->hasMany(Product::class);
}
}
and the Model Extra
class Extra extends Model {
use HasFactory;
protected $table = 'extra';
protected $guarded = [];
public function order(){
$this->belongsTo(Order::class);
}
}
and the Model product
class Product extends Model {
use HasFactory;
protected $table = 'product';
protected $guarded = [];
public function order(){
return $this->belongsTo(Order::class);
}
}
Now, from an API I receive data. With these data, I want to feed the models and then store the info to DB.
The approach there is atm is:
foreach ($list as $item) {
$order = new Order();
$order->id = $item['id'];
$order->title = $item['title'];
$order->save();
$extra = new Extra();
$extra->foo= $item['path']['to']['foo'];
$extra->bar= $item['path']['to']['bar'];
$order->extra()->save($extra)
$order->products()->createMany($item['path']['to']['products']);
}
The problem is that this code saves three times for each loop, one for order, one for extra, one for the product.
I would like to know if there is another way that I can use in order to gather the data inside the for-each and outside of it, to make something like
Order::insert($array_of_data);
I imagine it would look something like this, try it and if doesn't work please let me know i'll delete answer
$orders = [];
$extras = [];
$products = [];
foreach ($list as $item) {
$orders[] = [
'id' => $item['id'],
'title' => $item['title'],
];
$extras[] = [
'foo' => $item['path']['to']['foo'],
'bar' => $item['path']['to']['bar'],
];
$products[] = [
'order_id' => $item['id'],
'foo' => $item['path']['to']['products']['foo'] // or data it has
];
}
Order::insert($orders);
Extra::insert($extras);
Product::insert($products); // make sure each product has order id and data which is not visible here
I also suggest looking into converting $list into collection and then iterating over it, if the data is quite big you might make a use of LazyCollection which is the same as collection but better for processing larger data sets
Here's an example how you'd do it using lazy collection
LazyCollection::make($list)
->each(function (array $item) {
$order = Order::create(
[
'id' => $item['id'],
'title' => $item['title']
],
);
Extra::create(
[
'order_id' => $item['id'],
'foo' => $item['path']['to']['foo'],
'bar' => $item['path']['to']['bar'],
],
);
$order->products()->createMany($item['path']['to']['products']);
});
While it doesn't necessarily create many at once, it it memory saviour and will process quite quickly
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.
I've got the following function in a migration file. The migration is to add a new column, and then update the columns of the existing entries:
<?php
private function updatePlans()
{
$plans = PlanProvider::query()->get();
foreach ($plans as $plan) {
$plan->num_adults = 1;
if (stripos($plan->rate_name, 'couple') !== false) {
$plan->num_adults = 2;
}
$plan->save();
}
}
Now, what's happening here is that when I call save(), it's updating EVERY model, instead of the one inside the loop. I have a similar function for another migration, and it works as expected. Why would this update every model rather than just the one?
$plans is a Collection that contains all your "plans".
Your $plan->save(); is outside your if conditions, so obviously it updates every single row, no matter if it has 1 or 2 num_adults
public function store(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:subscribers'
]);
$subscriber = new Subscriber();
$subscriber->email = $request->email;
$subscriber->save();
Toastr::success('You are Successfully Added Our Subscriber List:)','Success');
return redirect()->back();
}
you can try this
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PlanProvider extends Model
{
protected $table = 'plan_provider';
protected $guarded = [];
public $timestamps = false;
}
private function updatePlans()
{
$plans = PlanProvider::findOrFail(id);
$plans->num_adults = 1;
$plans->save();
return redirect()->back();
}
I am trying to use ajax smart search,
http://maxoffsky.com/code-blog/laravel-shop-tutorial-3-implementing-smart-search/
But my application can not find the controller I used from the tutorial above.
This is the error i get:
Class App\Http\Controllers\Api\ApiSearchController does not exist
After googling this error message I found out that it is caused by an incorrect route. But I believe I set my routes correctly.
This is my route:
Route::get('api/search', 'Api\ApiSearchController#index');
And here is my controller:
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Base\Controller;
class ApiSearchController extends Controller {
public function appendValue($data, $type, $element)
{
// operate on the item passed by reference, adding the element and type
foreach ($data as $key => & $item) {
$item[$element] = $type;
}
return $data;
}
public function appendURL($data, $prefix)
{
// operate on the item passed by reference, adding the url based on slug
foreach ($data as $key => & $item) {
$item['url'] = url($prefix.'/'.$item['slug']);
}
return $data;
}
public function index()
{
$query = e(Input::get('q',''));
if(!$query && $query == '') return Response::json(array(), 400);
$products = Product::where('published', true)
->where('name','like','%'.$query.'%')
->orderBy('name','asc')
->take(5)
->get(array('slug','name','icon'))->toArray();
$categories = Category::where('name','like','%'.$query.'%')
->has('products')
->take(5)
->get(array('slug', 'name'))
->toArray();
// Data normalization
$categories = $this->appendValue($categories, url('img/icons/category-icon.png'),'icon');
$products = $this->appendURL($products, 'products');
$categories = $this->appendURL($categories, 'categories');
// Add type of data to each item of each set of results
$products = $this->appendValue($products, 'product', 'class');
$categories = $this->appendValue($categories, 'category', 'class');
// Merge all data into one array
$data = array_merge($products, $categories);
return Response::json(array(
'data'=>$data
));
}
}
I think the namespace you specified isn't the one expected :
Class App\Http\Controllers\Api\ApiSearchController does not exist
doesn't match :
<?php namespace App\Http\Controllers;