Push data in array after retrieval from Modal in Controller in Laravel - php

I am retrieving data from mysql database by help of modal in controller. As there is query which will run many times and I have to store all retrieval data into one array. I need to store data data in following mentioned format while it is not happening.
Controller code
class subcontroller extends Controller
{
public function Index(Request $req)
{
$arr=$req->get('myArray');
$data=[];
foreach($arr as $item){
$entry=item::where('jobtype',$item)->get();
array_push($data, $entry);
}
return $data;
}
}
Output
[[{"jobname":"Electrician","jobtype":"Electrical Wiring"}],[{"jobname":"Electrician","jobtype":"Electrical Work"}]]
Desire Result should be like:
[{"jobname":"Electrician","jobtype":"Electrical Wiring"},{"jobname":"Electrician","jobtype":"Electrical Work"}]

Eloquent actually has a neat little function built into the query builder. You can actually use an array in your query:
class subcontroller extends Controller
{
public function Index(Request $req)
{
$jobTypes = $req->get('myArray');
$itemCollection = DB::table('item')
->whereIn('jobtype', $jobTypes)
->get();
$data = $itemCollection->toArray();
return $data;
}
}
For more information, check out https://laravel.com/docs/8.x/queries#additional-where-clauses

Related

Having difficulties displaying all content on my wishlist table

I am trying to retrieve the data on my wishlist table, for a particular user, so far it only retrieves the first data on the table, just returning one array instead of the three in the table with same user id
public function getWishlistByUserId($id){
$wishlists = Wishlist::where('userId', $id)->get();
foreach($wishlists as $wishlist){
$products = Product::where('id', $wishlist->productId)->get();
return $products;
}
}
It happens because the foreach loop returns a value during the first iteration. Place your return statement outside the loop. Also you could improve your performence by making use of relationships.
An example could be:
// Product.php
public function wishlists()
{
return $this->hasMany(Wishlist::class);
}
// Your method
public function getWishlistByUserId($id)
{
return Product::whereHas('wishlists', function ($query) use ($id) {
$query->where('userId', $id);
});
}
Ideally this is n+1 situation
So i will suggest to use laravel relationship like:
in your whishlist model
public function product(){
return $this->hasMany(Product::class,'productId','id');
}
get data with relationship
public function getWishlistByUserId($id){
$wishlists = Wishlist::with('product')->where('userId', $id)->get();
}
I was finally able to get it working this way, i just pushed the result into an array, and then returned it outside the loop, thanks everyone for your help
public function getWishlistByUserId($id){
$wishlists = Wishlist::where('userId', $id)->get();
$wishlist = [];
foreach($wishlists as $wish){
$product = Product::where('id', $wish->productId)->get();
array_push($wishlist, $product);
}
return $wishlist;
}

Fetch data nested relations eloquent with() in Laravel

I have a model file "Student" that contains the relation :
public function implementations()
{
return $this->hasMany(Implementation::class);
}
In my Implementation model, I have theses relations :
public function score()
{
return $this->belongsTo(Score::class, 'id', 'implementation_id');
}
public function project()
{
return $this->belongsTo(Project::class);
}
I would like to retrieve a table with all its data.
I tried this
public function getStudents($id)
{
$event = Event::where('id', $id)->first();
$data = $event->students()->with('implementations')->get();
return response()->json($data);
}
It works. But I do not have the result I would like. I would also like to recover the implementations data with theproject and score relationships
I tried that but it does not work
public function getStudents($id)
{
$event = Event::where('id', $id)->first();
$data = $event->students()->with('implementations')->with('project', 'score')->get();
return response()->json($data);
}
Thank you very much for your help!
Have you tried Event::with('students', 'students.implementations') yet? You can eager load relations of relations using the dot notation.

How could I get Laravel 5.2 Pagination for a collection being sent to a view?

I am using Laravel 5.2 and using a polymorphic relations table for a feeds page. A feed has pictures, articles, and links that have their own respective models. The controller method that I am using for the feed looks like this:
public function index()
{
$allActivity = Activity::get();
$activity = collect();
foreach($allActivity as $act)
{
$modelString = $act->actable_type;
$class = new $modelString();
$model = $class->find($act->actable_id);
$activity->push($model);
}
return view('feed', compact('activity'));
}
and here is the feed.blade.php view
#foreach($activity as $class)
// Gives me the model name so the correct partial view could be referenced
<?php
$split = explode("\\", get_class($class));
$model = lcfirst($split[1]);
?>
#include("partials.{$model}", [$model => $class])
#endforeach
Because of this setup, I can't get pagination using the method outlined in the Laravel documentation. How could I correctly implement pagination using this setup? Any help would be greatly appreciated.
Access your relation using the actable() relation you should have on your Activity model. It will also help you avoid using find() in the loop like you are which will give you an N+1 issue.
In your activity model you should have an actable method:
class Activity
{
public function actable()
{
return $this->morphTo();
}
}
Then in your view you can lazy load all polymorphic actable relations and pass to the view. You can even keep your view clean and resolve the model name in the map() function:
public function index()
{
$activity = Activity::with('actable')->get()->map(function($activity) {
$activity->actable->className = lcfirst(class_basename($activity->actable));
return $activity->actable;
});
return view('feed', compact('activity'));
}
Then in your view:
#foreach($activity as $model)
#include("partials.{$model->className}", [$model->className => $class])
#endforeach
To run this with pagination it would be:
Controller:
public function index()
{
$activities = Activity::with('actable')->paginate(25);
return view('feed', compact('activities'));
}
View:
#foreach($activities as $activity)
#include('partials.'.lcfirst(class_basename($activity->actable)), [lcfirst(class_basename($activity->actable)) => $activity])
#endforeach

many to many attach() says trying to get property of non-object

I have two database tables journeys and stops that are related in a many-to-many relationship. There is also the third table journey_stop (the pivot table) for the relationship.
Models
Here is my Journey.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Journey extends Model
{
public function stops() {
return $this->belongsToMany('App\Stop');
}
}
and the Stop.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stop extends Model
{
public function journeys(){
return $this->belongsToMany('App\Journey');
}
}
Controller
Now in my controller, I have written a method changeStop(stop, journey_id) which takes a particular journey_id and either assigns a stop to it.(that is, creates a relationship between that particular stop and the journey) or removes the stop from the journey if it already exists.
Here is the method:
public function changeStop(Request $request, $id)
{
$stop = $request->all();
$journey = Journey::find($id);
if ($journey->stops()->contains($stop->id)) {
$journey->stops()->detach($stop->id);
}else{
$journey->stops()->attach($stop->id);
}
return $journey->stops();
}
But the line with the if statement throws the error:
Trying to get property of non-object
I have also tried using DB to query the pivot table directly but it throws the same error. Here's the code with DB:
public function changeStop(Request $request, $id)
{
$stop = $request->all();
$journey = Journey::find($id);
if (
DB::table('journey_stop')->where(
'journey_id',
$id
)->where(
'stop_id',
$stop->id
)->count() > 0
) {
$journey->stops->detach($stop->id);
} else {
$journey->stops->attach($stop->id);
}
return $journey->stops();
}
Everything seems right for me. But it doesn't work. What am I doing wrong?
Thanks for your time :)
You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table
$journey->stops()->sync([$stop_id])
And to work for your above code try this:
public function changeStop(Request $request, $id)
{
$stop = $request->all(); // returns an array
$journey = Journey::find($id);
if ($journey->stops->contains('id', $stop['id'])) {
$journey->stops()->detach($stop['id']);
} else {
$journey->stops()->attach($stop['id']);
}
return $journey->stops;
}

Paginate from model method data in CakePHP

I start with CakePHP framework. I want use paginator on my site but I wanted to do all the operations in the model.
When I use all in controller is OK:
public function index() {
$this->Paginator->settings = $this->paginate;
$data = $this->Paginator->paginate('MyModel');
$this->set('data', $data);
}
but when i want use method from model have problem with column: MyModel:
public function index() {
$this->Paginator->settings = $this->paginate;
$data = $this->Paginator->paginate($this->MyModel->getData());
$this->set('data', $data);
}
//model method
public function getData()
{
$data = $this->find('all');
return $data;
}
ofc when I display this method without paginate is ok:
public function index() {
$data = $this->MyModel->getData();
$this->set('data', $data);
}
Friend you are trying to apply the pagination on the "array" not on the model. Cakephp provide the functionality to pagination data for the model instance. As the model data transaction method have the database connection object and the pagination component manage that object.

Categories