skip to Main Content

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');
}

2

Answers


  1. 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
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search