I'm working on a php project but I have a problem with the database , I use this code to get data from the database :
public function getSeenAction(Request $request , $notificationId)
{
$sessionId = $request->headers->get('SessionID');
if( $sessionId == null )
{
//return new Response("Unauthorized",401);
}
$notificationRepo = $this->getDoctrine()->getRepository('MegasoftEntangleBundle:Notification');
$notification = $notificationRepo->findOneById($notificationId);
if($notification == null)
{
return new Response("Notification not found" ,404);
}
$seen = $notification->getSeen();
$response = new JsonResponse();
$response->setdata(array('seen'=>$seen));
$response->setStatusCode(200);
return $response;
}
I tried the same code with other tables and it worked , but whenever I retrive data from the Notification table it always give null , although the table contains the data.
$notificationRepo = $this->getDoctrine()->getRepository('MegasoftEntangleBundle:Notification');
$notification = $notificationRepo->findAll();
var_dump(notification);
Is this code returns you something ? Probably the code of your NotificationRepository.php is not good, can you put it on ?
Try using find instead of findOneById if you just want to find record by Id.
On the other hand if you want to use findOneBy the passed argument for criteria should be an array.
$result = $notificationRepo->find($notificationId);
Or
$result = $notificationRepo->findOneBy(array('id' => $notificationId));
Or
make sure you have a proper code for findOneById in your NotificationRepository.php file
Then you can check
if (!empty($result)) { ... }
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
}
It's been a while since I've used Laravel and I'm pulling my hair out over the below issue, seems to be relatively straight forward and probably 100% obvious.
I'm adding some new fields to an existing view, I've created a new model, added the relations and added the fields. I can confirm that I'm able to view the data on the View successfully, I can take the data from the view successfully and insert a new record on the target table.
The problem I'm having is I'm unable to update an existing record, I can retrieve the record by ID, but I can't use the object selector ($object->data) on it, I've added the function and the comments below:
//Create the license
$license = License::where('id', $venue->license_id)->get();
if(empty($license->id))
{
Log::notice("Nothing to show");
} else {
//I have added this in as a sanity check, I've been able to
//perform Log::notice($license); successfully but the below doesn't work?
Log::notice($license->id);
Log::notice($license->license_name);
}
//This works, I am able to create a new License if there is no ID set.
$license_class_id = $request->get('license_class_id');
$license_type_id = $request->get('license_type_id');
$liquor_license_no = $request->get('liquor_license_no');
$site_reference_no = $request->get('site_reference_no');
$holder_name = $request->get('holder_name');
$license_name = $request->get('license_name');
$trading_name = $request->get('trading_name');
//This works
if( !$license || !$license->exists ) {
$license = new License;
}
//This is to update the object but it doesn't seem to happen.
$license->license_class_id = $license_class_id;
$license->license_type_id = $license_type_id;
$license->liquor_license_no = $liquor_license_no;
$license->site_reference_no = $site_reference_no;
$license->holder_name = $holder_name;
$license->license_name = $license_name;
$license->trading_name = $trading_name;
if ( ! $license->save() ) {
return $license->errors();
}
if(!empty($license->id))
{
$venue->license_id = $license->id;
}
if ( ! $venue->save() ) {
return $venue->errors();
}
use update() method for update not save(). save() is used at the insert time
$license->update();
And fetch record as single collection. If id is not primary key then by below way
//Create the license
$license = License::where('id', $venue->license_id)->first();
And if id is primary key then you directly get by
$license = License::find($venue->license_id);
You can use updateOrCreate method here too.
By this code,
//Create the license
$license = License::where('id', $venue->license_id)->first();
if(empty($license))
{
Log::notice("Nothing to show");
} else {
//I have added this in as a sanity check, I've been able to
//perform Log::notice($license); successfully but the below doesn't work?
Log::notice($license->id);
Log::notice($license->license_name);
}
//This works, I am able to create a new License if there is no ID set.
$license_class_id = $request->get('license_class_id');
$license_type_id = $request->get('license_type_id');
$liquor_license_no = $request->get('liquor_license_no');
$site_reference_no = $request->get('site_reference_no');
$holder_name = $request->get('holder_name');
$license_name = $request->get('license_name');
$trading_name = $request->get('trading_name');
License::updateOrCreate([
'license_class_id' => $license_class_id ,
'license_type_id' => $license_type_id,
'license_type_id' => $license_type_id,
'license_type_id' => $license_type_id,
'holder_name' => $holder_name,
'license_name' => $license_name,
'trading_name' => $trading_name
]);
For more information check this link.
If you will use this method, You do not need to check if a record exists or not. That is the advantage.
I want to update a product in laravel, but it does not work properly,
my Controller's update method looks like this:
public function updateProduct(Request $request)
{
# Get input values
$data = $request->all();
$productID = $data['id'];
$product = Product::find($productID);
$product->fill($data);
# Validate input
$validator = Validator::make($request->all(), Product::$rules);
if ($product->save())
{
# save language selection
$lsCounter = 0;
$langSelecName = $request->input('language');
$langSelecFile = $request->file('language');
if ($langSelecName)
{
$projectPath = $dProjectPath . "languages";
foreach ($langSelecName as $langSelecNameKey => $langSelecNameValue)
{
if ($langSelecFile[$lsCounter]['input_vid_lang'] != null)
{
$langVidFileName = $langSelecFile[$lsCounter]['input_vid_lang']->getClientOriginalName();
$languages = new Language();
$languages['short_name'] = $langSelecNameValue;
$languages['input_video'] = $projectLangPath . '\\' . $langVidFileName;
$languages->product()->associate($product);
$langData = [
'languagesShortName' => $languages['short_name'],
'languagesInputVideo' => $languages['input_video']
];
$intProductID = intval($productID);
$findLangId = $languages->find($intProductID);
$findLangId->fill($langData);
if ($languages->save())
{
$langSelecFile[$lsCounter]['input_vid_lang']->move($projectLangPath, $langVidFileName);
}
}
$lsCounter++;
}
}
} else {
return redirect()->route('editProduct', $productID)->with('message', 'Error')->withInput();
}
I get the following error after I try to update it, the error looks like this:
Call to a member function fill() on null
And it points to this line:
$findLangId->fill($langData);
I appreciate some help, thank you.
Edit
Ok people said that $intProductRomID is null, but I get the correct product id if I dd($intProductRomID).
As per the comments, the following line is return null:
$findLangId = $languages->find($intProductRomID);
Meaning this won't be valid:
$findLangId->fill($langData);
In other words, if you were to var_dump out $languages->all(), you will not find $intProductRomID in there. If you are unsure, swap out ->find with ->findOrFail() (which, considering you aren't doing any error catching or checking, you probably should be using it instead).
Edit
After some conversation in the comments, it has been established that the wrong field was being used for reference. Use a where instead:
$languages->where('product_rom_id', $intProductRomID);
I'm doing webservice using laravel,Here I need to send response after the value get updated into database...
I tried something like this,
public function getPhoneverify(){
$_REQUEST['user_id'] = str_replace('"','', $_REQUEST['user_id']);
$_REQUEST['status'] = str_replace('"','', $_REQUEST['status']);
$user = \DB::table('tb_users')->where('id', $_REQUEST['user_id'] )->update(array('phone_verified' => $_REQUEST['status']));
if($user)
{
echo "success";exit;
}
else
{
echo "failed";exit;
}
}
But here,always it shows the else part message,even if the value get updated into the database..
How should I do this..
Is there any other option to do this!!..
Someone help me..
If you need to check if the query was successful, I'd suggest a different approach. Assuming the user_id field is unique, following should work:
$user = \DB::table('tb_users')->where('id', $_REQUEST['user_id'] )->first();
Or you can also retrieve the user like this:
$user = \DB::table('tb_users')->find($_REQUEST['user_id']);
And then update/save it:
$user->fill(array('phone_verified' => $_REQUEST['status']));
$saved = $user->save(); //this will always return true or false.
if($saved)
{
echo "success";exit;
}
else
{
echo "failed";exit;
}
You can use exception handling if you want
try {
$user = \DB::table('tb_users')->where('id', $_REQUEST['user_id'] )->update(array('phone_verified' => $_REQUEST['status']));
}catch(\Exception $e){
//write statements here if query fails
}
By the way as far I know DB::update() returns boolean
The return value will never be true since it returns the number of rows affected by the database transaction.
So you should check for the integer value, not if it is true or false
I have a function that I use to get the user id of Auth component. It works fine without use return json_encode. The problem is that I need this works with json_encode because I get values from ajax request.
Using json_encode it always return null to id and I can't understand why does it occur. The problem is with the function indexAjax() below.
How could I use $this->Auth->user("id") with json_encode and it not return null ?
Trying.
//using $this->set it works fine
public function index() {
$id = $this->Auth->user("id");
$empresas = $this->Empresa->find('all', array(
'fields'=>array("id", "nomeFantasia", "cnpj",
"telefone1", "telefone2", "celular", "aberto"),
'conditions'=>array("users_id = "=> $id)
));
debug($id) or die;
//$this->set(compact('empresas'));
}
//with json_encode always return null
public function indexAjax() {
$this->autoRender = false;
$id = $this->Auth->user("id");
$empresas = $this->Empresa->find('all', array(
'fields'=>array("id", "nomeFantasia", "cnpj",
"telefone1", "telefone2", "celular", "aberto"),
'conditions'=>array("users_id = "=> $id)
));
return json_encode($id);
}
solved the problem. My solution was when user make login I get the user id and write in session so when I need this id I get from session directly and not from AuthComponent.
It works.