How to check duplicate title and not save to database in laravel - php

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
}

Related

Update database using foreach in laravel

I want to insert new data in database using API, but first, i want to check the database using $po_transaction, it exist or not, if $po_transaction exist, do updated. But when i am input same data, it changed all data with one value
This is my database, when first insert:
and this is my database, when i am input same data (This the issue):
This is my controller:
public function post_data(Request $request){
$po_transaction = $request->input('po_transaction');
$data = $request->input('data');
$decode_data = json_decode($data);
if(!$decode_data){
return response()->json(['message'=>'No Data','success'=>0]);
}
$po_id = Produk::where('po_transaction','=', $po_transaction)->first();
// if po_id exist, update the data
if ($po_id) {
foreach ($decode_data as $item => $value) {
DB::table('produk')
->where('po_transaction', $po_transaction)
->update(['po_transaction'=>$po_transaction, 'nama_produk'=>$value->produk, 'harga_jual'=>$value->price]);
}
return response()->json(['message'=>'success, data saved','success'=>1]);
}else{
// if po_id not exist, create new
foreach($decode_data as $item => $value)
{
$saveTransaction = new Produk();
$saveTransaction->po_transaction = $po_transaction;
$saveTransaction->nama_produk = $value->produk;
$saveTransaction->harga_jual = $value->price;
$saveTransaction->save();
}
if($saveTransaction->save()){
return response()->json(['message'=>'success, data saved','success'=>1]);
}else{
return response()->json(['message'=>'no data saved','success'=>0]);
}
}
}
and for data, i am using json data like this:
[
{"produk":"shampoo","price":"12000"},
{"produk":"noodle","price":"110200"},
{"produk":"cup","price":"1000"}
]
This is decode_data:
How to fix this issue, when i input same data, it not only change all data with one value?
You need to specify which record you actually want to update by proving the id in the where clause like this:
DB::table('produk')
->where([
'po_transaction' => $po_transaction,
'id_produk'=> $value->id,
])
->update([
'po_transaction'=>$po_transaction,
'nama_produk'=>$value->produk,
'harga_jual'=>$value->price,
]);
You can use this method <model_name>::updateOrCreate() to Create/Update in single method.
Produk::updateOrCreate(['po_transaction'=>$po_transaction,'nama_produk'=>$value->produk],['harga_jual'=>$value->price]);
for more info look at this https://laravel.com/docs/5.7/eloquent

$casts, array data

I'm using $casts to save data in array to database. I have an issue with that.
How can i push data to an existing array in the database?
For example i have already an array of data in my db column like: ["some_data", "another_el"] and so on and in the Controller i want to push in this array in db some other data from input.
$brand = Brand::find($request->input('brand'));
$brand->model = $request->input('model');
$brand->update();
Pushing data like this.
You cannot do this with Eloquent's Mass Assignment functions (update, create, etc). You must pull down your field, change it, then save the model.
$collection = collect($brand->field);
$collection->push($myNewData);
$brand->field = $collection->toJson();
$brand->save();
Way 1
$brand = Brand::find($request->input('brand'));
$brand->model = array_merge($brand->model, [$request->input('model')]);
$brand->update();
Way 2 (my favorite because it encapsulates the logic)
$brand = Brand::find($request->input('brand'));
$brand->addModel($request->input('model'));
$brand->update();
And on Entity:
public function addModel($value)
{
$this->model = array_merge($this->model, [$value]);
}
Optional
And on Entity (instead $casts):
public function setModelAttribute($value)
{
$this->attributes['model'] = json_encode($value);
}
public function getModelAttribute($value)
{
return json_decode($value, true);
}

replicate() method not found in laravel 5.2

I am trying to replicate table row and its relationship.
but I am getting error message that replicate() does not exist,
I have seen on stackoverflow that many have used replicate() without any issue, but i am getting this error
my controller code
public function copyshowtime($cinema_id,$show_date)
{
$date=new Carbon($show_date);
$current_show_date=$date->format('Y-m-d');
$next_show_date=$date->addDay()->format('Y-m-d');
$movieshowtime=Movies_showtimes::with('showdata')->where([['cinema_id','=',$cinema_id],['show_date','=',$current_show_date]])->get();
$newshowtime=$movieshowtime->replicate();
return $newshowtime;
}
Is there any namespace i have to use for using replicate() , I am unable to get solution from laravel website also.
help is appreciated.
You can use replicate() on a model but not on a collection.
By fetching your records using get() you are returning a collection.
If you are just expecting one record to be returned then replace get() with first() and then replicate() should exist as it will be returning an instance of the model rather than a collection:
public function copyshowtime($cinema_id,$show_date)
{
$date=new Carbon($show_date);
$current_show_date=$date->format('Y-m-d');
$next_show_date=$date->addDay()->format('Y-m-d');
$movieshowtime=Movies_showtimes::with('showdata')->where([['cinema_id','=',$cinema_id],['show_date','=',$current_show_date]])->first();
$newshowtime=$movieshowtime->replicate();
return $newshowtime;
}
You will also need to save() the $newshowtime.
This code worked perfectly for me
public function copyshowtime($cinema_id,$show_date)
{
$date=new Carbon($show_date);
$current_show_date=$date->format('Y-m-d');
$next_show_date=$date->addDay()->format('Y-m-d');
$movieshowtime=Movies_showtimes::with('showdata')->where([['cinema_id','=',$cinema_id],['show_date','=',$current_show_date]])->get();
foreach ($movieshowtime as $item)
{
$item->show_date=$next_show_date;
$item->show_id=NULL;
$newshowtime=$item->replicate();
$newshowtime->push();
foreach ($item->showdata as $sd)
{
$newshowdata = array(
'showdata_id' => NULL,
'show_id'=>$newshowtime->id,
'category_id'=>$sd->category_id,
'showdata_category'=>$sd->showdata_category,
'showdata_rate'=>$sd->showdata_rate
);
// print_r($newshowdata);
Movies_showdata::create($newshowdata);
}
}
return redirect()->back();
}
Any suggestions to improve this code will be appreciated.
This type of function would help to clone multiple records and add those records in the same table. I tried a similar code flow and worked.
/**
* Clone multiple records in same table
*
* #params int $cinemaId
* #params string $showDate
*
* #return bool $status
*
* #access public
*/
public function copyShowTime($cinemaId, $showDate)
{
$date = new Carbon($showDate);
$currentShowDate = $date->format('Y-m-d');
// Cloned & Create new records
$moviesShowTimeCollection = Movies_showtimes::with('showdata')->where([['cinema_id','=',$cinemaId],['show_date','=',$currentShowDate]])->get();
// Please check that Model name should change according to camelCases - Movies_showtimes to MoviesShowtimes
if(!$moviesShowTimeCollection->isEmpty()) {
$moviesShowTimeData = $moviesShowTimeCollection->toArray();
foreach ($moviesShowTimeData as $key => $value) {
$primaryKey = 'show_id'; // Needs to check the table primary key name
$primaryId = $value[$primaryKey];
$moviesShowTimeObj = Movies_showtimes::find($primaryId);
// below code can modify while cloaning
//$clonedMoviesShowTimeObj = $moviesShowTimeObj->replicate()->fill([
// 'column_name' => $updatedValue
//]);
$clonedMoviesShowTimeObj = $moviesShowTimeObj->replicate(); // just to clone a single record
$status = $clonedMoviesShowTimeObj->save();
}
}
}
Cheers!
You can easily replicate rows with new changes in that rows
$apcntReplicate = TrademarkApplicantMap::where('trademark_id', $trdIdForPostAssesment)->get();
foreach($apcntReplicate as $oldapnctdata)
{
$apcntreplicated = $oldapnctdata->replicate() ;
//update row data which will newly created by replicate
$apcntreplicated->row_name = $newrowdata;
//save new replicated row
$apcntreplicated->save();
}
Don't use toArray() then each element in the foreach loop will be an Eloquent object.

How to access a certain GET data in CakePHP?

I am currently writing an adress book and using a framework (CakePHP) an MVC for the first time. Unfortunately I have some trouble.
I want to realize the following:
In case the URL is
/contacts/view/
I want to show all contacts in a list. In case there is an id given after /view/, e.g.
/contacts/view/1
I just want to display the contact with the id 1. (complete different view/design than in the first case)
My ContactsController.php is the following
public function view($id = null){
if(!$this->id){
/*
* Show all users
*/
$this->set('mode', 'all');
$this->set('contacts', $this->Contact->find('all'));
} else {
/*
* Show a specific user
*/
$this->set('mode','single');
if(!$this->Contact->findByid($id)){
throw new NotFoundException(__('User not found'));
} else {
$this->set('contact', $this->Contact->findByid($id));
};
}
}
But "$this->mode" is always set as "all". How can I check whether the id is set or not?
I really want to avoid "ugly" URL-schemes like ?id=1
Thanks in advance!
Your code is only meeting the if part and its not going to else part. Use (!$id)..
$_GET data is retrieved through the URL. In CakePHP this means it's accessed through that method's parameters.
I'm arbitrarily picking names, so please follow! If you're in the guests controller and posting to the register method you'd access it like this
function register($param1, $param2, $param3){
}
Each of these params is the GET data, so the URL would look something like
www.example.com/guests/param1/param2/param3
So now for your question How can I check whether the id is set or not?
There are a couple of possibilities. If you want to check if the ID exists, you can do something like
$this->Model->set = $param1
if (!$this->Model->exists()) {
throw new NotFoundException(__('Invalid user'));
}
else{
//conduct search
}
Or you can just search based on whether or not the parameter is set
if(isset($param1)){ //param1 is set
$search = $this->Model->find('all','conditions=>array('id' => $param1)));
}
else{
$search = $this->Model->find('all');
}
You should only change the conditions not the whole block of code like
public function view($id = null){
$conditions = array();
$mode = 'all';
if($id){
$conditions['Contact.id'] = $id;
$mode = 'single';
}
$contacts = $this->Contact->find('all', array('conditions' => $conditions));
$this->set(compact('contacts', 'mode'));
}

Dealing with url request in CodeIgniter

I just started learning codeigniter and i must say its pretty easy but I have a problem dealing with wrong urls, for example:
if I have an anchor tag like this
http://example.com/info/2
in the controller if I have
public function info( $x ) {
$data['body'] = "Personal_info";
$data['details'] = $this->person_model->get_detail( $x );
$this->load->view('view', $data);
}
the controller grabs the links
segment (3)
and then grab the details of the id from the database.
now for instance if a user manually edit the link on the browser and change the
segment(3)
to lets say 7 and there is no id in the database as 4.
how do I handle such a problem? I am a beginner so please pardon me
You could use empty method to check if there is data and if not redirect away from the page.
public function info( $x )
{
$details = $this->person_model->get_detail( $x );
if(empty($details))
redirect('other/url');
$data['body'] = "Personal_info";
$data['details'] = details;
$this->load->view('view', $data);
}
This way it doesn't throw errors and potentially attempt to display something that doesn't exist.
you can check if the passed id exists in database before trying to fetch related data, like:
$data_exists = $this->person_model->data_exists( $x );
if( $data_exists ) {
$data['details'] = $this->person_model->get_detail( $x );
$this->load->view('view', $data);
}
else {
//load some view for showing no such id exists in db
}
where data_exists() can be a function in model which returns TRUE or FALSE depending on existance of your id in database.

Categories