I need to be able to use an array in session please. I want to store diffrents candidate_id to find the candidates later.
CandidateController :
public function search(Request $request)
{
$data=$request->validate([
'keyword' => 'required',
'word' => 'required',]);
$keyword= $data['keyword'];
$key= $data['key'];
$candidate = candidate::where($key, $keyword)->get();
return view('candidate.list', compact('candidate'));
}
what are the changes that I should do to make a session array that contains [candidate's ids]
and then finding those $candidate using these ids, and return view('candidate.list', compact('candidate')) ? is it possible ?
$candidate = candidate::where($key, $keyword)->get();
after this line loop through the $candidate.
$ids = [];
foreach ($candidate as $obj){
$ids = $obj->candidate_id;
}
session()->push('candidate_ids', $ids);
return view('candidate.list', compact('candidate'));
when you need to get this array from the session just
#foreach (Session::get('candidate_ids') as $id)
{{$id}}
#endforeach
Related
I am using Laravel for controller and blade file for a webpage. My code is something like:
PropertiesController
$properties = Property::where('status', 1);
$properties = $properties->orderBy('properties.created_at', 'DESC')->paginate(8);
return view('properties.index')->with('properties', $properties);
in index.blade.php
#foreach ($properties as $property)
<div class="geo">
<span class="lat">{{ $property->title }}</span>,
<span class="lng">{{ $property->description }}</span>
</div>
what I want to achieve is to get categories w.r.t. counts along with properties, for that, I am doing
$properties = Property::where('status', 1);
$categories = array();
if (is_null($req->c)) {
$search = $properties;
foreach (Category::all() as $category) {
array_push(
$categories,
array(
'id' => $category->id,
'name' => $category->category,
'counts' => count($search->where('properties.category', $category->id)->get()),
)
);
}
}
$properties = $properties->orderBy('properties.created_at', 'DESC')->paginate(8);
return view('properties.index')->with('properties', $properties)->with('categories', $categories);
$search = $properties; and
'counts' => count($search->where('properties.category', $category->id)->get()),
with this it gives me
Trying to get property of non-object
<span class="lat"><?php echo e($property->title); ?></span>,
What I think is you want to pass your data to blade view and get counts of categorized data with each category... For that, you can use duplicated functions to count your data separately. e.g.:
public function properties() {
$properties = Property::where('status', 1);
$categories = array();
foreach (Category::all() as $category) {
$count = $this->count($category->id);
array_push(
$categories,
array(
'id' => $category->id,
'name' => $category->category,
'counts' => $count,
)
);
}
$properties = $properties->orderBy('properties.created_at', 'DESC')->paginate(8);
return view('properties.index')->with('properties', $properties)->with('categories', $categories);
}
public function count($id) {
$count = count(Property::where('category_id', $id)); // or any variable you are using to connect categories table with
return $count;
}
$count = $this->count($category->id);
This is the line which did the trick.
If the relationships are made in the models you should only use with () in this way.
This is how the controller should be.
$properties = Property::where('status', 1)->with('category')->orderBy('properties.created_at', 'DESC')->paginate(8);
return view('properties.index', compact('propierties'));
This will give you the list of Properties next to the assigned category.
But if you need to list the categories and have in each category the properties you must do this.
$categories = Category::with('properties')->paginate(8);
return view('properties.index', compact('categories'));
In my PHP code, I noticed that I can access my value only with a foreach. Can anyone explain why?
return view('pages.temp_page_course', [
'page' => $this->course($slug),
]);
public function course($slug)
{
$course = Course::where('slug', $slug)->get();
return $course;
}
With this code, I can access the value.
#foreach($page as $key => $course)
{{ $course->title }}
#endforeach
How do I access the value without doing a foreach?
Thank you very much
$course = Course::where('slug', $slug)->get(); will fetch an array of courses.
Try first() instead, $course = Course::where('slug', $slug)->first(); will fetch only 1 and will remove the need for the loop.
Replace get() with toArray(), that will load results into $course as an array so you can access it as an array
public function course($slug)
{
$course = Course::where('slug', $slug)->toArray();
return $course;
}
How do I get a model from the database and then convert it to an Array including extra information using the with statement.
public function edit($id) {
// convert product to array;
$product = Product::findOrFail($id)->with('supplier', 'category');
$data = [
'suppliers' => Supplier::all()->pluck('company', 'id'),
];
// cannot merge because $product is object and cannot turn into array
// the only way I know to convert to array is doing this
// $product->first()->toArray() but this gets the first item in the database
$product = array_merge($product, $data);
return response()->json($product, 200, ['Content-Length' => strlen(json_encode($product))]);
}
You could use Laravel's collection helper to make it simple:
collect($product)->toArray()
Then you should be able to do:
$product array_merge(collect($product)->toArray(), $data);
What about this:
$return = [
'suppliers' => Supplier::all()->pluck('company', 'id'),
'product' => $product // or $product->toArray()
];
return response()->json($return, 200);
If you need the suppliers to be an attribute of the product, you could try this:
$productArr = $product->toArray();
$productArr['suppliers'] = Supplier::all()->pluck('company', 'id');
return response()->json($productArr, 200);
I'm new to Laravel and at the moment I have a piece of code in a Controller which without the while loop it works, it retrieves my query from the database.
public function dash($id, Request $request) {
$user = JWTAuth::parseToken()->authenticate();
$postdata = $request->except('token');
$q = DB::select('SELECT * FROM maps WHERE user_id = :id', ['id' => $id]);
if($q->num_rows > 0){
$check = true;
$maps = array();
while($row = mysqli_fetch_array($q)) {
$product = array(
'auth' => 1,
'id' => $row['id'],
'url' => $row['url'],
'locationData' => json_decode($row['locationData']),
'userData' => json_decode($row['userData']),
'visible' => $row['visible'],
'thedate' => $row['thedate']
);
array_push($maps, $product);
}
} else {
$check = false;
}
return response()->json($maps);
}
I am trying to loop through the returned data from $q and use json_decode on 2 key/val pairs but I can't even get this done right.
Don't use mysqli to iterate over the results (Laravel doesn't use mysqli). Results coming back from Laravel's query builder are Traversable, so you can simply use a foreach loop:
$q = DB::select('...');
foreach($q as $row) {
// ...
}
Each $row is going to be an object and not an array:
$product = array(
'auth' => 1,
'id' => $row->id,
'url' => $row->url,
'locationData' => json_decode($row->locationData),
'userData' => json_decode($row->userData),
'visible' => $row->visible,
'thedate' => $row->thedate
);
You're not using $postdata in that function so remove it.
Do not use mysqli in Laravel. Use models and/or the DB query functionality built in.
You're passing the wrong thing to mysqli_fetch_array. It's always returning a non-false value and that's why the loop never ends.
Why are you looping over the row data? Just return the query results-- they're already an array. If you want things like 'locationData' and 'userData' to be decoded JSON then use a model with methods to do this stuff for you. Remember, with MVC you should always put anything data related into models.
So a better way to do this is with Laravel models and relationships:
// put this with the rest of your models
// User.php
class User extends Model
{
function maps ()
{
return $this->hasMany ('App\Map');
}
}
// Maps.php
class Map extends Model
{
// you're not using this right now, but in case your view needs to get
// this stuff you can use these functions
function getLocationData ()
{
return json_decode ($this->locationData);
}
function getUserData ()
{
return json_decode ($this->userData);
}
}
// now in your controller:
public function dash ($id, Request $request) {
// $user should now be an instance of the User model
$user = JWTAuth::parseToken()->authenticate();
// don't use raw SQL if at all possible
//$q = DB::select('SELECT * FROM maps WHERE user_id = :id', ['id' => $id]);
// notice that User has a relationship to Maps defined!
// and it's a has-many relationship so maps() returns an array
// of Map models
$maps = $user->maps ();
return response()->json($maps);
}
You can loop over $q using a foreach:
foreach ($q as $row) {
// Do work here
}
See the Laravel docs for more information.
I have a car_properties table,
My table like:
id , name , value
I have a big form to create a car. There are 40 different inputs. Some of them selectboxes, some of them checkboxes.. I am trying to implement Eav model for this.
I want to add this 40 inputs in one method
I have methods like:
public function set_property($key ,$value){
$set = new CarProperties;
$set->name = $key;
$set->value = $value;
$set->save();
}
public function Createcar(Request $request){
set_property('gearbox',$request->get('gearbox'));
set_property('fuel_type',$request->get('fuel_type'));
..
..
}
What is the proper way to do this? Or can use a foreach or..?
Thanks for help.
You can try something like this:
public function CreateCar(Request $request)
{
foreach ($request->all() as $key => $value)
{
CarProperties::create([
'name' => $key,
'value' => $value
]);
}
}