Passing data between 2 models in 1 controller function laravel - php

I need to get the lecture id in my student table and from then only can i get the lecture's data using that id. The problem is, the $lectureID is null when i try to apply it on the lecture model, but when i check on the console, it does get the data. Thanks in advance.
Controller
public function getLecture($id)
{
$lectureID = student::select('lecture_id_FK')->where('student_id',$id)->first();
$lectureDATA = lecture::where('lecture_id',$lectureID)->first();
return $lectureDATA;
}

you can try two ways
public function getLecture($id)
{
## way 1
$lectureID = student::where('student_id',$id)->value('lecture_id_FK');
$lectureDATA = lecture::where('lecture_id',$lectureID)->first();
## way 2
$lectureID = student::where('student_id',$id)->first();
$lectureDATA = lecture::where('lecture_id',$lectureID->lecture_id_FK)->first();
return $lectureDATA;
}

before check what inside $lectureID:
public function getLecture($id)
{
$lectureID = student::select('lecture_id_FK')->where('student_id',$id)->first();
dd($lectureID);//I believe inside will be object with lecture_id_FK
//then just
$lectureDATA = lecture::where('lecture_id',$lectureID->lecture_id_FK)->first();
return $lectureDATA;
}
Recommended way to do it:
In Student model class ( recommend use capital S )
class student
{
public function lecture(){
return $this->hasOne('App\lecture','lecture_id_FK','lecture_id');
}
}
then just load studen with lecture like this
$student = studend::with('lecture')->find($id);
$lecture = $student->lecture;

Related

laravel perform two query in one function

Simply i have a two table
GALLARIES AND MEDIA
In a GALLARIES table id,title,venueId i have saved gallary folder name for the particular venue.
In MEDIA Table I have id,imagepath,is_thumb(0 or 1),gallery_Id
What i want to do is when i set is_thumb_image(1) then i have call two function
1 st for unset image all with gallery_id and after i call second function for set is_thumb_image for particular image.
Is it possible to call one function only and perform both functionalty.
Here is my Controller code.
$albumId = $request->album_id; //table galleries id - album name
if($request->is_thumb_image == "true") {
$media1->UnsetThumbImage($albumId); // first unset thumb_image
$media->setThumbImage($media->id); // call for set thumb_image
} else {
$request->is_banner_image = false;
}
Here is my model functions
public function setThumbImage($mediaId) {
try {
DB::table('media')
->where('id', $mediaId)
->update(['is_thumb_image' => 1]);
$this->is_thumb_image = 1;
} catch (\Exception $ex) {
echo $ex->getMessage();
dd($ex->getTraceAsString());
}
}
public function UnsetThumbImage($albumid) {
DB::table('media')
->where('gallery_id', $albumid)
->update(['is_thumb_image' => 0]);
$this->is_thumb_image = 1;
}
How can i do it calling only one function.
You can use CASE with MySQL to update on various conditions. You'd need to use a raw query to do this with Laravel I believe.
Something like:
UPDATE media
SET is_thumb_image = CASE
WHEN id = $mediaId THEN 1
WHEN gallery_id = $albumId THEN 0
END
For that you need to:
specify which column is it gonna be. But best practice is to do this in different methods, as they have different jobs, and column action.
$this->setThumbImage('id', $id);
$this->setThumbImage('gallery_id', $id);
Pass what you need to according to your requirement.
public function setThumbImage($id, $field) {
DB::table('media')
->where("$field", $id)
->update(['is_thumb_image' => 0]);
$this->is_thumb_image = 1;
}

Save attribute of model in database in PHP in OctoberCMS

Hi I have problem when i tried to save attribute of model to database. I write in OctoberCMS and i have this function:
public function findActualNewsletter()
{
$actualNewsletter = Newsletter::where('status_id', '=', NewsletterStatus::getSentNowStatus())->first();
if (!$actualNewsletter) {
$actualNewsletter = Newsletter::where('send_at', '<=', date('Y-m-d'))->where('status_id', NewsletterStatus::getUnsentStatus())->first();
$actualNewsletter->status_id = NewsletterStatus::getSentNowStatus();
dd($actualNewsletter);
}
return $actualNewsletter;
}
getSentNowStatus()=2;
getUnsentStatus()=1;
dd($actualNewsletter) in my if statement show that status_id = 2 But in database i still have 1. I used this function in afterSave() so i dont need:
$actualNewsletter->status_id = NewsletterStatus::getSentNowStatus();
$actualNewsletter->save();
becosue i have error then i use save in save.
Of course i filled table $fillable =['status_id']. And now i dont know why its not save in database when it go to my if. Maybe someone see my mistake?
If you are trying to modify the model based on some custom logic and then save it, the best place to put it is in the beforeSave() method of the model. To access the current model being saved, just use $this. Below is an example of the beforeSave() method being used to modify the attributes of a model before it gets saved to the database:
public function beforeSave() {
$user = BackendAuth::getUser();
$this->backend_user_id = $user->id;
// Handle archiving
if ($this->is_archived && !$this->archived_at) {
$this->archived_at = Carbon\Carbon::now()->toDateTimeString();
}
// Handle publishing
if ($this->is_published && !$this->published_at) {
$this->published_at = Carbon\Carbon::now()->toDateTimeString();
}
// Handle unarchiving
if ($this->archived_at && !$this->is_archived) {
$this->archived_at = null;
}
// Handle unpublishing, only allowed when no responses have been recorded against the form
if ($this->published_at && !$this->is_published) {
if (is_null($this->responses) || $this->responses->isEmpty()) {
$this->published_at = null;
}
}
}
You don't have to run $this->save() or anything like that. Simply modifying the model's attributes in the beforeSave() method will accomplish what you desire.

Loop to get user data

I can't put real code here because is very long and will be hard to
explain.
I have users table in database and I have data table in database too.
So, to get the user data I'll pass user_id as parameter. Like this:
public function get_user_data($user_id) {
}
But. I can only get 1 data per "request". (Keep reading)
public function user_data() {
$getUsers = $this->db->get('users');
foreach($getUsers->result_array() as $user)
{
$data = $this->get_user_data($user->ID);
var_dump($data); // Only return 1 data;
}
}
But, I guess that have an way to "bypass" this but I don't know. I'm having trouble thinking.
As I said, I want to "bypass" this, and be able to send multiple user IDs, my real function do not accept that by default and can't be changed.
Thanks in advance!
replace
foreach($getUsers->result_array() as $user)
{
$data = $this->get_user_data($user->ID);
var_dump($data); // Only return 1 data;
}
to this
foreach($getUsers->result_array() as $user)
{
$data[] = $this->get_user_data($user->ID);
}
var_dump($data);
If you are aiming at sending more data to the function, you always need to make signature change of your function as one of the below :
function get_user_data() {
$args = func_get_args();
/** now you can access these as $args[0], $args[1] **/
}
Or
function get_user_data(...$user_ids) {
/** now you can access these as $user_ids[0], $user_ids[1] **/
}
// Only higher version of PHP
But I am not sure how you will handle returning data.
EDIT: Yes, then in the function, you can collect data in array and return an array of data from function.
If you can change in your function from where to where_in I think you will get an easy solution.
public function get_user_data($user_ids)
{
// your db code
$this->db->where_in('ID',$user_ids); //replace where with where_in
}
public function user_data()
{
$getUsers = $this->db->get('users');
foreach($getUsers->result_array() as $user)
{
$user_ids[] = $user->ID;
}
$this->get_user_data($user_ids);
}

Getting the value of a row in CodeIgniter

I am trying to get the value of a row in the database but not working out that well. I not sure if can work like this.
I am just trying to get the value but also make sure it from the group config and the key.
Model
function getTitle() {
return $this->db->get('setting', array(
->where('group' => 'config'),
->where('key' => 'config_meta_title'),
->where('value'=> ) // Want to be able to return any thing in the value
))->row();
}
In the controller I would do this:
function index() {
$data['title'] = $this->document->getTitle();
$this->load->view('sample', $data);
}
First, you have this line set to this:
$data['title'] $this->document->getTitle();
That should be an = assignment for $this->document->getTitle(); like this:
$data['title'] = $this->document->getTitle();
But then in your function you should actually return the setting value from your query with row()->setting:
function getTitle() {
return $this->db->get('setting', array(
->where('group' => 'config'),
->where('key' => 'config_meta_title'),
->where('value'=> ) // Should return this row information but can not.
))->row()->setting;
}
But that said, I am unclear about this:
->where('value'=> ) // Should return this row information but can not.
A WHERE condition is not a SELECT. It is a condition connected to a SELECT that allows you to SELECT certain values WHERE a criteria is met. So that should be set to something, but not really sure what since your code doesn’t provide much details.
Found Solution Working Now. For Getting Single Item From Database In Codeigniter
Loading In Library
function getTitle($value) {
$this->CI->db->select($value);
$this->CI->db->where("group","config");
$this->CI->db->where("key","config_meta_title");
$query = $this->CI->db->get('setting');
return $query->row()->$value;
}
Or Loading In Model
function getTitle($value) {
$this->db->select($value);
$this->db->where("group","config");
$this->db->where("key","config_meta_title");
$query = $this->db->get('setting');
return $query->row()->$value;
}

How to submit data to multiple tables in the same form

I have 2 tables: listings and listings_specifications
Listings table
id
type
status
location
specifications_id
Listings_specifications table
id
listing_id
swimming_pool
water_well
I need to select the specifications (checkboxes) on the same form with which I add a listing. I have created all the forms, views, models, controllers but I think I got some logic wrong.
Listing.php model
protected $table = 'listings';
public function contact()
{
return $this->BelongsTo('contacts');
}
public function specifications()
{
return $this->BelongsTo('listings_specifications');
}
Specification.php model
protected $table = 'listings_specifications';
public function listings()
{
return $this->BelongsTo('listings');
}
ListingsController.php (where the data gets saved in the database)
$listing = new Listing;
$contact = new Contact;
$listing->status = Input::get('status');
$listing->listingfor = Input::get('listingfor');
$listing->propertystatus = Input::get('propertystatus');
$listing->propertytype = Input::get('propertytype');
$listing->userid = Auth::user()->id;
$listing->location = Input::get('location');
$listing->contact_id = $contact_id;
$listing->save();
$specifications = Specification::find($id);
if( $listings->save() ) {
$specifications = new Specification;
$specifications->listing_id = $id;
$specifications->swimming_pool = Input::get('swimming_pool');
$specifications->water_front = Input::get('water_front');
$specifications->save();
}
I'm getting this error: Undefined variable: id
Where did I go wrong?
Thank you
It looks like you have some logic errors.
First of all, you are never setting $id anywhere, but that's okay because you really don't need it.
Remove the $specifications = Specification::find($id); line because that's not doing anything.
Then change your last section to something like this...
if( $listings->save() ) {
$specifications = new Specification;
$specifications->swimming_pool = Input::get('swimming_pool');
$specifications->water_front = Input::get('water_front');
$listing->specifications()->save($specifications);
}
$listing->specifications()->save($specifications); will automatically save the new specification with the correct listing_id for you.
Modify your Listing model's specifications relationship to...
public function specifications()
{
return $this->hasMany('Specification');
}
I'm assuming here one listing can have many specifications. If not, you can easily just change that to a hasOne.
You use $id in the line $specifications = Specification::find($id); but you don't define it before.

Categories