My user relationship is :
public function country()
{
return $this->belongsTo(Country::class);
}
and the query is :
$user = User::with('country')->first();
I want to check if the country is empty replace that with a default data or anything
so first I tried like this :
if(empty($user->country)){
$user->country = "some default value";
}
and It didn't work after searching I try this :
if(empty($user->country)){
$user->setRelation('country' , 'some default value');
}
and again it doesn't work for me. the "setRelation" remove the country key in the user's object
If empty / null received in eloquent result relation key, then set defaultOject can be set as follows:
For single relation:
$modelInstance = $modelInstance->setRelation('relationName', $relationModelObject)
For multiple relation:
$modelInstance = $modelInstance->setRelation('relationName', collect([$relationModelObject]))
Multiple relation example:
$defaultMedia = new Media;
$defaultMedia->id = 0;
$defaultMedia->file_name = 'defaultImage.jpg';
$result = Post::with('media')->get();
$result->transform(function ($post, $key) use($defaultMedia) {
if($post->media->count() == 0) {
$post->setRelation('media', collect([$defaultMedia]));
}
return $post;
});
return $result;
Now, in final $result you shall get $defaultMedia when relation returned null.
It does not work that way because country is not a direct attribute/column of the user.
You can change your code like this.
if(empty($user->country)){
$user->country->update([
'name' => "some default value"
]);
}
Hope it works. :-)
Related
i have a problem that when i get data from other api and want if same title wont save to api. Each time getting data from the api is 20 and want to save it to the database without duplicate. Please help me. Thank you very much!!!
public function getTitle($title){
$title = $this->posts->where('title', $title)->get();
return $title;
}
public function getApi(Request $request){
$url = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=87384f1c2fe94e11a76b2f6ff11b337f";
$data = Http::get($url);
$item = json_decode($data->body());
$i = collect($item->articles);
$limit = $i->take(20); // take limited 5 items
$decode = json_decode($limit);
foreach($decode as $post){
$ite = (array)$post;
$hi = $this->getTitle($ite['title']);
dd($ite['title'], $hi);
if($ite['title']==$hi){
dd('not save');
}
else{
dd('save');
}
//dd($hi, $ite['title']);
// create post
$dataPost = [
'title'=>$ite['title'],
'description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']
];
//dd($dataPost);
//$this->posts->create($dataPost);
}
return redirect()->route('posts.index');
}
You can use first or create for saving data in database if title name is new. using firstOrNew you dont have to use any other conditions
for example:-
$this->posts->firstOrCreate(
['title' => $ite['title']],
['description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']]);
firstOrNew:-
It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new Model after applying any attributes passed in the second parameter
From docs
If any records exist that match your query's constraints, you may use
the exists and doesntExist methods
if($this->posts->where('title', $title)->doesntExist())
{
// save
} else {
// not save
}
Inside the $get_user and $get_code queries they both have a group_id.
I have dd(); them Both and made 100% sure.
the $get_user query has multiple group_id's and the $get_code only has one group_id which is equal to one of the $get_user group_id's.
The goal at the moment is to create a group_id match query.
Get the code that has a group ID equal to one of the $get_user group_id's
public function getCodesViewQr($code_id)
{
$userid = Auth::id();
$get_user = GroupUser::all()->where('user_id',$userid);
$get_code = Code::all()->where('id',$code_id);
$group_match = GroupUser::where('group_id', $get_code->group_id);
$view['get_users'] = $get_user;
$view['get_codes'] = $get_code;
$view['group_matchs'] = $group_match;
return view('codes.view_qr_code', $view);
}
The group match query does not work. $get_code->group_id does not get the code group_id.
If there is a match then set $match equal to rue. else $match is False
$group_match = GroupUser::where('group_id', $get_code->group_id);
I'm using two Models Code and GroupUser
My Code table is like this :
-id
-group_id (This is the only on important right now)
-code_type
My GroupUser table is like this :
-id
-group_id (This is the only on important right now)
-user_id
-user_role
I have linked the Models
Inside my Code Model I have the relationship to GroupUser
public function group_user()
{
return $this->belongsto('App\GroupUser');
}
And Inside my GroupUser Model I have the relationship to Code
public function code()
{
return $this->belongsto('App\Code');
}
Inside My Code controller I have included my models.
use App\Code;
use App\GroupUser;
Hi guys so I had some help from a guy I work with and this is the solution he came up with. We made a few adjustments. all the Databases and results stayed the same. we just changed the method we used to get the results.
I really appreciate all the help from #linktoahref
public function view_code($random)
{
$code = Code::where('random', $random)->first();
$view['code'] = $code;
if ($code->code_type == 1)
{
// Its a coupon
if (!empty(Auth::user()))
{
// Someones is logged in
$user = Auth::user();
$view['user'] = $user;
$user_groups = GroupUser::where('user_id',$user->id)->pluck('group_id')->toArray();
if (in_array($code->group_id, $user_groups))
{
// The user is an admin of this code
return view('view_codes.coupon_admin', $view);
}else
{
// Save the code to that users account
return view('view_codes.generic_code', $view);
}
}else
{
// Anon
return view('view_codes.coupon_anon', $view);
}
}elseif ($code->code_type == 2)
{
// Voucher..
}else
{
// We don't know how to deal with that code type
}
}
$get_code = Code::find($code_id);
// Check if the code isn't null, else give a fallback to group_id
$group_id = 0;
if (! is_null($get_code)) {
$group_id = $get_code->group_id;
}
$group_match = GroupUser::where('group_id', $group_id)
->get();
$match = FALSE;
if ($group_match->count()) {
$match = TRUE;
}
I have a list of properties for a real estate application and im trying to implement a like/unlike functionality based on each property detail. The idea is to add a like or remove it matching the current property and user. This is my code so far, but it only remove likes so it doesnt work as expected. If anyone can suggest for a better approach ill be appreciated.
//Controller
public function storeLike($id)
{
$like = Like::firstOrNew(array('property_id' => $id));
$user = Auth::id();
try{
$liked = Like::get_like_user($id);
}catch(Exception $ex){
$liked = null;
}
if($liked){
$liked->total_likes -= 1;
$liked->status = false;
$liked->save();
}else{
$like->user_id = $user;
$like->total_likes += 1;
$like->status = true;
$like->save();
}
return Redirect::to('/detalle/propiedad/' . $id);
}
// Model
public static function get_like_user($id)
{
return static::with('property', 'user')->where('property_id', $id)
->where('user_id', Auth::id())->first();
}
// Route
Route::get('store/like/{id}', array('as' => 'store.like', 'uses' => 'LikeController#storeLike'));
#Andrés Da Viá Looks like you are returning object from model. In case there is no data in database, it will still return an object - so far my guessing. Can you do something like below in the if($liked){ code?
Try this instead:
if(isset($liked -> user_id)){
Also try to print $liked variable after try and catch blocks. Use var_dump.
If this still does not work for you then let me know. I will try to create code based on your question.
Fix it by adding a where clause in my model to make the status equal to True ->where('status', 1)->first();
Okay, so I have this snippet of code in a controller. However, it's all DB driven and should really be in model - I get that. However, as you can see in the IF statement, I need to pass along $data to my view. Based on the outcome. I tried pasting this chuck of coding in a method in my model (calling the model method via controller), however the $data[update_prompt] string is not getting called by the view...
How would I translate this code into a model - sending the $data values back to my controller to embed in my view?
// show appropriate upgrade message if user has free account
$id = $this->session->userdata('user_id');
$this->db->select('subscription'); // select the subscription column
$this->db->where('id', $id); //find id in table that matches session id
$query = $this->db->get("subscriptions"); // connect to this database
$subscribe = $query->result_array(); //returns the result of the above
if($subscribe[0]['subscription'] == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
{
$data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
}
else
{
$data['update_prompt'] = '';
}
You would add a function in your model, like so:
public function myModelFunction($id) {
//we return row as we are looking up by primary key and are guaranteed only one row
return $this->db->select('subscription')
->where('id', $id)
->get('subscriptions')
->row();
}
Then, in your controller:
public function myControllerFunction() {
$subscribe = $this->my_model->myModelFunction($this->session->userdata('id'));
if($subscribe->subscription == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
{
$data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
}
else
{
$data['update_prompt'] = '';
}
}
I'm trying to pass a variable other than $id for a view function in my 'Texts' controller:
public function view($postid = NULL) {
$this->Text->postid = $postid;
$this->set('text', $this->Text->read());
}
What am I doing wrong?
what are you doing there?
you can use read only with the primary key - id usually
$this->Text->id = $postid;
Is the $primaryKey property of your Text model set to 'postid'? If not, then $this->Text->read() is not going to work like you want. In app/Model/Text.php, add this to your class:
public $primaryKey = 'postid';
You could also do the following if you don't want to change your primary key (but you probably should change it):
$text = $this->Text->find('first', array(
'conditions' => array('postid' => $postid),
));
$this->set('text', $text);
Also, try adding something like this to your view to see what's actually in your variable:
<pre><?php var_dump($text); ?></pre>
That might give you a better idea of what's going on.
Lastly, here's some relevant documentation:
Model Attributes
Retrieving Your Data
You can customize your view function as:
public function view($name = NULL) {
$record = $this->Text->findByName($name);
$this->set('text', $record);
}
Here name is a string. The name field should be present in the database.
You can see the content of $record by debugging.debug($record).
Figured it out:
public function view($postid = NULL) {
$post = $this->Text->find('first', array('conditions' =>
array('Text.postid'=>$postid)));
$this->set('text', $post);
}