How to get the Last data from Database using Laravel - php

I am trying to get a column of the last data in the database but so far, I am getting all the data in the database in an array.
This is my code;
public function NewID(){
$adminid=Auth::user()->admin_id;//cooperative ID
$newid = Member::select('member_id')->where('admin_id', '=',$adminid)->get();
return View::make('admin.member.addmember')
->with('NewID', $newid);
}
I have updated the code to be this base on suggestions;
public function NewID(){
$adminid=Auth::user()->admin_id;//cooperative ID
$newid = Member::select('member_id')->where('admin_id', '=',$adminid)->orderBy('id', 'desc')->first();
return View::make('admin.member.addmember')
->with('NewID', $newid);
}
and I am using a For Loop to display data on the view
#foreach ($NewID as $NewIDs)
{{$NewIDs->member_id}}
#endforeach
My error is now ErrorException:Trying to get property of non-object
Answer
I finally got it to work
I used this instead
public function NewID(){
$adminid=Auth::user()->admin_id;//cooperative ID
$newid = Member::select('member_id')->where('admin_id', '=',$adminid)->orderBy('id', 'desc')->take(1)->get();
return View::make('admin.member.addmember')
->with('NewID', $newid);
}

I finally got it to work
I used this instead
public function NewID(){
$adminid=Auth::user()->admin_id;// ID
$newid = Member::select('member_id')->where('admin_id', '=',$adminid)->orderBy('id', 'desc')->take(1)->get();
return View::make('admin.member.addmember')
->with('NewID', $newid);
}

Well, a lot of things could be wrong, so what you should do is find the cause. In you view file, temporarily remove the foreach loop and replace it with {{ dd($NewID) }}. This will 'dump and die' the value of $NewID.
Additionally, I suggest you stick to variable naming conventions. Variables should start lowercase. Also it is confusing to call a collection of Members NewID and a single instance of a member NewIDs. Sticking to the convention helps you and others to read and debug your code.

Related

Too few arguments for view error with laravel

I'm having a problem with laravel., I'm trying to send the variable $codes on my view :
$codes = Code::where('user', $id)->get();
return view('user.edit', ['user' => $user,'codes' => $codes]);
But I get that error Too few arguments to function e(), 0 passed in
The variable $user goes well but not the variable code, anyone have an idea for a solution?
Thank you all
use this:-
return view('user.edit')->with('codes',$codes);
you can get the user with :-
Auth::user()->name;
I'm pretty sure, if you are following Laravel naming conventions, in your eloquent query the column name is user_id and not user. Also if you are using such querys, and you have foreign, you can define relations in your models, like the following:
Code Model
public function user
{
$this->belongsTo(User::class);
}
User Model
public function codes
{
$this->hasMany(Code::class);
}
Instead of line
$codes = Code::where('user', $id)->get();
You can go with:
$codes = $user->codes();
If you don't have the foreigns in your database
$codes = Code::where('user_id', $id)->get();
If non of these helps, please dd() your variables before returning the view, and share result with me in comment. In laravel 7 how you return view is good.

Search criteria based on few parameter Laravel

This search works for me only when I fill all the fields correctly. My wish is that when I fill only one field, I will exclude results only relevant to this field.
Example if I fill only 'mark' field with 'Audi' got my mark name. My function is currently returning the results only if all fields are filled. If I fill one field, it returns an empty array. Also, I'm not sure if this function is well written, I followed the tutorial. Look code:
public function searchFilterCar(Request $request, Car $car){
if($request->has('car_type')){
if($request->has('mark')){
if($request->has('model')){
if($request->has('fuel')){
if($request->has('circuit')){
return $car->where('car_type', $request->input('car_type'))
->where('mark', $request->input('mark'))
->where('model', $request->input('model'))
->where('fuel', $request->input('fuel'))
->where('circuit', $request->input('circuit'))
->get();
}
}
}
}
}
}
Separate the conditions into several if statements, the where works on the existing results so you will be continuing from previous where. Its should something like this:
if($request->has('car_type')){
$car = $car->where('car_type', $request->input('car_type'));
}
if($request->has('mark')){
$car = $car->where('mark', $request->input('mark'));
}
....
return $car->get();
It might look a bit crude but it decreases the size of the code block and it works
Another way similar to Khaldoun Nd's answer would be to use query conditionals. It allows you to remove the subsequent if statements.
The code would become something like that:
return $car
->when($request->car_type, function ($query, $type) {
return $query->where('car_type', $type);
})
->when($request->mark, function ($query, $mark) {
return $query->where('mark', $mark);
})
// Chain the other conditions like the previous ones...
->get();
For reference: https://laravel.com/docs/5.8/queries#conditional-clauses

Passing a parameter to a custom find method in cakephp 3.x

I want to build a custom find function that retrieves bands for a given genre, i have tried this but the function can't access to the parameter $genre:
public function findGenre(Query $query, array $options)
{
$genre = $options['genre'];
$bands = $this->find()->contain([
'Genres' => function($q){
return $q->where(['Genres.id' => $genre]);
}
]);
return $bands;
}
I can access the $genre outside the contain() method, but not inside it.
My question is, how can i pass the $genre var to the function($q) inside the contain method.
I found where the problem is, i had to use the keyword use after the function($q), so that part of the code will look like this
$bands = $this->Bands->find()->contain('Genres', function($q) use ($genre){
return $q->where(['Genres.name'=>$genre]);
});
Also,the contain() method returns all the data even if the bands don't belong to a genre, but when i replaced it with matching() it worked just fine.
I hope this will help anyone who is having a similar problem in the future.
I was facing same issue but now it's resolved. I will explain you step by step:
My tables are:
articles: id,name,status,created
tags:id,name,status,created
articles_tags: id,article_id, tag_id
my query is this:
I want to pass my $tag_data['slug'] in matching variable but
directly this variable is not working in query. So I put in simple
$uses variable and now it's working properly.
$uses = $tag_data['slug'];
$contain_article = ['Tags'];
$query = $this->Articles->find('All')
->where(['Articles.status' => '1'])
->contain($contain_article)
->matching('Tags', function ($q) use ($uses) {
return $q->where(['Tags.slug' => $uses]);
});
Please try this :-)

Only last row getting displayed in view in Codeigniter

I'm trying to fetch certain values from and then pass it to another model in the same control.
However I'm only able to display the last row in the view.
I have shared my code below and I'm not sure where I'm going wrong.
Controller:
public function test($id){
$mapping_details = $this->queue_model->get_mapping_details($id);
foreach ($mapping_details as $value) {
$data['agent_details'] = array($this->agent_model->get_agent_details($value['user_id']));
}
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Model:
public function get_agent_details($id) {
$query = "select * from user_table where id = ".$id." and company_id = ".$this->session->userdata('user_comp_id');
$res = $this->db->query($query);
return $res->result_array();
}
Welcome to StackOverflow. The problem is the iteration in your controller. You are iterating through the $mapping_details results and per every iteration you are re-assigning the value to $data['agent_details'] , thus losing the last stored information. What you need to do is push to an array, like this:
foreach ($mapping_details as $value) {
$data['agent_details'][] = $this->agent_model->get_agent_details($value['user_id']);
}
However, wouldn't it be best if you created a query that uses JOIN to get the related information from the database? This will be a more efficient way of creating your query, and will stop you from iterating and calling that get_agent_details() over and over again. Think of speed. To do this, you would create a model method that looks something like this (this is just an example):
public function get_mapping_details_with_users($id){
$this->db->select('*');
$this->db->from('mapping_details_table as m');
$this->db->join('user_table as u', 'u.id=m.user_id');
$this->db->where('m.id', $id);
$this->db->where('u.company_id', $this->session->userdata('user_comp_id'));
return $this->db->get()->result();
}
Then your controller will only need to get that model result and send it to the view:
public function test($id){
$data['details_w_users'] = $this->queue_model->get_mapping_details_with_users($id);
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Hope this helps. :)

Undefined Variable Multiple Query Scopes Laravel

This work perfect:
public function scopeHBO($query)
{
return $query ->where('network', '=', "hbo");
}
Call in Controller: It Works!
$events = Schedule::HBO()->orderBy('searchdate')->get();
When I add another Query Scope like so:
public function scopeHBO($query)
{
return $query
->where('network', '=', "hbo")
->where('searchdate', '>=', 'NOW()');
}
OR:
public function scopeDate($query)
{
return $query->where('searchdate', '>= ', 'NOW()');
}
Then call in the controller:
$events = Schedule::HBO()->Date()->orderBy('searchdate')->get();
I get an error: Undefined variable: event. I tried with with Raw MySql in the same model and it works. Whenever i add a query scope, does not matter what it is.. i get that same error Undefined variable: event.
NOW() is a function, so you need to use a raw query:
where('searchdate', '>=', DB::raw('NOW()'))
Then you can use the scopes. (Do note that I think scopeDate must be called as date(), not Date() - not 100 % sure on that though.)
This sounds less like a generic problem with Laravel, and more like a problem with you specific application.
My guess (which is a wild guess), is that adding that second where clause in your scope method
return $query
->where('network', '=', "hbo")
->where('searchdate', '>=', 'NOW()');
ended up creating a SQL query that returned 0 rows. Then, somewhere in your other code you're doing something like
foreach($events as $event)
{
//...
}
//referencing final $event outside of loop
if($event) { ... }
As I said, this is a wild guess, but the problem doesn't seem to be your query code, the problem seems to be the rest of your code that relies on the query returning a certain number of, or certain specific, rows/objects.

Categories