Select from mysql table through variable Laravel - laravel

I want to select those uniname with same seller_id.There can be multiple uniname with same seller id. I am getting the seller_id info from html, where seller_id is passed as id. How to call it through controller for printing. The line I used is,
$university = DB::table('universities')->where('seller_id', '$id');
public function manage_seller_profile($id)
{
$divisions = Division::orderBy('id','asc')->get();
$districts = District::orderBy('id','asc')->get();
$seller_profile = Seller_info::find($id);
$university = DB::table('universities')->where('seller_id', '$id');
return view('Backend.pages.seller.manage_seller_profile', compact('seller_profile', 'districts', 'divisions', 'university'));
}

You need to remove these single quotes, and add the Laravel ORM select and get functions.
Your code will look like this:
$university = DB::table('universities')->where('seller_id', '=', $id)->select('uniname')->get();
I put the '=' operator to make the code more readable.

Related

Get laravel relations value as attribute

I have two models, Portal and Tag and relation many-to-many between them with extra database portal_tag. All working great and I can access to portal->tag without problem.
But my goal is to get this model like "all values from model" and all relations value as one attribute, between commas. Is it possible?
Because I need it inside PortalsExport class in this form to use in export into CSV libary.
Now its look like this:
Portal::with('tags')
->select('url','type','topic','description','prohibited','visits','facebook_url','twitter_url','instagram_url')
->where('user_id', Auth::id())->get();
I have no idea how to make tags.name same as all other options from select.
If you want to get tags relations as comma separated string then One approach is, You will need to define a accessor in your Portal model which will append you tags array into string. like once I was did in one of my project:
Step 1:
public function getTagsAsStringAttribute(): string
{
$array = $this->tags->pluck('name')->all();
return implode(", ",
array_map(function ($k, $v) {
return $k;
}, array_keys($array), array_values($array))
);
}
In above closure functions, plz verify yourself that you tag name value is available in $k or $v variable.
Step 2:
add that accessor in Portal model append array like that:
protected $appends = [
'tags_as_string',
];
Step 3:
In the result of yours below query you will get tags_as_string attribute which contains comma separated tags as string.
Portal::with('tags')
->select('url','type','topic','description','prohibited','visits','facebook_url','twitter_url','instagram_url')
->where('user_id', Auth::id())->get();
If tags_as_string shown empty then try it above query without select() clause.

Eloquent how to pass parameters to relationship

The code I'm trying to fix looks like this. I have an Hotel class which is used in a query to get all hotels in an area but it doesn't discard those which are not available. There's a method inside which should be an accessor but it's not written the way I expected it to be:
public function isAvailableInRanges($start_date,$end_date){
$days = max(1,floor((strtotime($end_date) - strtotime($start_date)) / DAY_IN_SECONDS));
if($this->default_state)
{
$notAvailableDates = $this->hotelDateClass::query()->where([
['start_date','>=',$start_date],
['end_date','<=',$end_date],
['active','0']
])->count('id');
if($notAvailableDates) return false;
}else{
$availableDates = $this->hotelDateClass::query()->where([
['start_date','>=',$start_date],
['end_date','<=',$end_date],
['active','=',1]
])->count('id');
if($availableDates <= $days) return false;
}
// Check Order
$bookingInRanges = $this->bookingClass::getAcceptedBookingQuery($this->id,$this->type)->where([
['end_date','>=',$start_date],
['start_date','<=',$end_date],
])->count('id');
if($bookingInRanges){
return false;
}
return true;
}
I wanted to filter out hotels using this query. So this is the query from the controller:
$list = $model_hotel->with(['location','hasWishList','translations','termsByAttributeInListingPage'])->get();
Is it possible to pass the range of days to the function?
By the way the first thing I tried was to use the collection after the query and pass a filter function through the collection and after that paginate manually but although it does filter, but apparently it loses
the "Eloquent" result set collection properties and it ends up as a regular collection, thus it doesn't work for me that way.
Maybe the best approach for that is to create a query scope (source) and put all your logic inside of this function.
after that you can call this scope and pass the dates. Example you will create a query scope and paste your code inside of it.
public function scopeisAvailableInRanges($query, $start_date, $end_date) {
}
then you will invoke this query scope in your controller like this.
$list = $model_hotel::isavailableinranges($start_date, $end_date)->with(['location','hasWishList','translations','termsByAttributeInListingPage'])->get();
keep in mind that inside of your query scope you will return a collection. A collection of all your available hotels.

How to make conditions in a laravel query, based on returned value of a helper function

I'm using Laravel 5.7. I have a 'Match' model whose first participant name is returned from a helper function getFirstParticipant(Match $match).
I am trying to get certain matches from DB whose first participants are e.g. 'John'. Is it possible that I use Eloquent query functions to do so for example something like this?
Match::where('firstParticipant', 'John')
or any other solutions?
I am copying my helper function below if it can help to declare the problem:
function getFirstParticipant(Match $match)
{
$structure_id = $match->structure_id;
$seed = $match->matchResult->first_seed;
$placement = Placement::where('structure_id', $structure_id)->where('seed', $seed)->first();
return !empty($placement->player_id) ? $placement->player->username : $placement->team->name;
}
Just sub a variable into the second parameter.
$first = getFirstParticipant(Match $match);
Match::where('firstParticipant', $first->first_name)->get();
Obviously I'm assuming some variable names here such as first_name. But you should be able to follow that. Just use your helper to return a model value and insert that returned value as the second parameter of the where argument.
No, there is no way. Database design issues aside, the only way I can see this working is by using collection methods.
Match::get()->filter(function ($match) {
return $match->firstParticipant == 'John'; // Or is it getFirstParticipant($match) ?
})->all();
# Laravel 6.x introduces LazyCollections
Match::cursor()->filter(function ($match) {
return $match->firstParticipant == 'John'; // Or is it getFirstParticipant($match) ?
})->all();

Get specific values from controller function

I started learning Laravel and I am trying to achieve the following:
Get data from database and display specific field.
Here is my code in the controller:
public function show()
{
$students = DB::select('select * from students', [1]);
return $students;
}
Here is my route code:
Route::get('', "StudentController#show");
That all works for me and I get the following displayed:
[{"id":1,"firstname":"StudentFirstName","lastname":"StudentLastName"}]
How can I get only the "lastname" field displayed?
Thanks in advance!
DB::select('select * from students')
is a raw query that returns an array of stdClass objects, meaning you have to loop through the array and access properties:
$students[0]->lastname
You can also use the query builder to return a collection of objects:
$collection = DB::table('students')->get();
$student = $collection->first();
$student->lastname;
Lastly, using the query builder, you can use pluck or value to get just the last name. If you only have one user, you can use value to just get the first value of a field:
DB::table('students')->where('id', 1)->value('lastname');
I strongly advise you to read the Database section of the Laravel docs.
$students[0]['lastname'] will return the last name field, the [0] will get the first student in the array.
I would recommend creating a model for Students, which would make your controller something like this:
$student = Students::first(); // to get first student
$student->lastname; // get last names
If you only want the one column returned, you can use pluck()
public function show()
{
$last_names= DB::table('students')->pluck('lastname');
return $last_names;
}
This will return an array of all the students' lastname values.
If you want just one, you can access it with $last_names[0]
As a side note, your show() method usually takes a parameter to identify which student you want to show. This would most likely be the student's id.
There are several ways you can accomplish this task. Firstly, I advise you to use the model of your table (probably Students, in your case).
Thus, for example,to view this in the controller itself, you can do something like this using dd helper:
$student = Students::find(1);
dd($student->lastname);
or, using pluck method
$students = Students::all()->pluck('lastname');
foreach($students as $lastName) {
echo $lastName;
}
or, using selects
$students = DB::table('students')->select('lastname');
dd($students);
Anyway, what I want to say is that there are several ways of doing this, you just need to clarify if you want to debug the controller, display on the blade...
I hope this helps, regards!

trying to Fetch Single record from table in laravel using ajax

here is my code that i write in route file
`Route::get('/{username}/ajax-lead', function(){
$brand_id = Input::get('brand_id');
$table_data = DB::table('users')->where('brand_id',$brand_id)->get();
$table_name = $table_data[0]->table_name;
$table_lastRecords = DB::table($table_name)->get();
$columns = Schema::getColumnListing($table_name);
$table_lastRecords = DB::table($table_name)->get();
return Response::json($table_lastRecords);
});`
here is my view file
`{{Form::open(array('url'=>'','files'=>true))}}
client list *
Select Clients
#foreach($brand as $userLeads){
brand_id }}">{{ $userLeads->name }}
}
#endforeach
{{Form::close()}}
$('#brand_name').on('change',function(e){
// body...
console.log(e);
var brand_id = e.target.value;
//ajax Call
$.get('/{username}/ajax-lead?brand_id=' + brand_id,function(data){
//success data
console.log(data);
});
});
`
i want to get table_name column value in response. i use json for response.
ANSWER: Your easiest solution would be to return an array of data, where the first value is the table_name and the second value is the collection of lastRecords. It would look something like this:
$responseArray[0] = $table_name;
$responseArray[1] = $table_lastRecords;
return json_encode($responseArray);
Then, in your view, you would parse your Json response and let table_name = responseData[0] and lastRecords = responseData[1]. Of course, you could also use non-numeric indices to make the code more readable, such as responseData['table_name'], but those semantics are up to you.
ADDITIONAL INFO:
With that said, there are several issues with your code that I feel I should point out. You should become more familiar with Eloquent queries, as using them properly will greatly simplify your code. For instance, these two lines:
$table_data = DB::table('users')->where('brand_id',$brand_id)->get();
$table_name = $table_data[0]->table_name;
Could be re-written as:
$table_name = User::where('brand_id',$brand_id)->first()->table_name;
But this makes me ask the question, is there only one table per brand? If so, why do you store this information with the user, and not in a 'brands' table? The way that this would make the most sense would be to have a Brands model that has a table_name column, and you would get the table name with this simple query:
$table_name = Brand::find($brand_id)->table_name;
In addition, you should avoid doing this type of work in your routes file. Anything not related specifically to ROUTING the user should be handled in the controller or model. Then, within your controller, you should be utilizing the User or Brand model in your queries by importing App\User and App\Brand.

Resources