Sending $data Variable From Model To View - php

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'] = '';
}
}

Related

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

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
}

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.

How to reroute to another view when a resource doesn't exist in a table (Laravel 4)

I have a resource:
Route::resource('artists', 'ArtistsController');
For a particular url (domain.com/artists/{$id} or domain.com/artists/{$url_tag}), I can look at the individual page for a resource in the table artists. It is controlled by this function:
public function show($id)
{
if(!is_numeric($id)) {
$results = DB::select('select * from artists where url_tag = ?', array($id));
if(isset($results[0]->id) && !empty($results[0]->id)) {
$id = $results[0]->id;
}
}
else {
$artist = Artist::find($id);
}
$artist = Artist::find($id);
return View::make('artists.show', compact('artist'))
->with('fans', Fan::all())
->with('friendlikes', Fanartist::friend_likes())
->with('fan_likes', Fanartist::fan_likes());
}
What I would like to do is have all urls that are visited where the {$id} or the {$url_tag} don't exist int he table, to be rerouted to another page. For instance, if I typed domain.com/artists/jujubeee, and jujubee doesn't exist in the table in the $url_tag column, I want it rerouted to another page.
Any ideas on how to do this?
Thank you.
In your show method you may use something like this:
public function show($id)
{
$artist = Artist::find($id);
if($artist) {
return View::make('artists.show', compact('artist'))->with(...)
}
else {
return View::make('errors.notfound')->withID($id);
}
}
In your views folder create a folder named errors (if not present) and in this folder create a view named notfound.blade.php and in this view file you'll get the $id so you may show something useful with/without the id.
Alternatively, you may register a global NotFoundHttpException exception handler in your app/start/global.php file like this:
App::error(function(Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
// Use $e->getMessage() to get the message from the object
return View::make('errors.notfound')->with('exception', $e);
});
To redirect to another page have a look at the redirect methods available on the responses page of the Laravel docs.
This is how I would go about doing it and note that you can also simplify your database queries using Eloquent:
public function show($id)
{
if( ! is_numeric($id)) {
// Select only the first result.
$artist = Arist::where('url_tag', $id)->first();
}
else {
// Select by primary key
$artist = Artist::find($id);
}
// If no artist was found
if( ! $artist) {
// Redirect to a different page.
return Redirect::to('path/to/user/not/found');
}
return View::make('artists.show', compact('artist'))
->with('fans', Fan::all())
->with('friendlikes', Fanartist::friend_likes())
->with('fan_likes', Fanartist::fan_likes());
}

MySQL error 1054 when I try more than one model call from a controller function in CodeIgniter

I want to write a function which will take a series of fields and input different values into a different databases. Right now it is only two separate database entries but I hope to implement more later. I want to input a new Saint into one table and then, if the user fills in the 'ofRegion' field, I want that to be stored in a different table. My problem comes about when the model tries to input the information for 'ofRegion.' I get a MySQL error ( 1054 ) stating there is an unknown column. I can see by the MySQL error that it is trying to input all the information from the previous entry as well as the new information. How do I clear the old information? Can I even do this or will I need multiple models for each table I want to enter information into?
Model Functions
public function input_saint($newSaintID)
{
//grab values from post stream
$this->saintID = $newSaintID;
$this->active = 1;
$this->nameFirst = $this->input->post('nameFirst');
$this->nameLast = $this->input->post('nameLast');
$this->gender = $this->input->post('gender');
$this->martyr = $this->input->post('martyr');
$this->nationality = $this->input->post('nationality');
$this->feastMonth = $this->input->post('feastMonth');
$this->feastDay = $this->input->post('feastDay');
$this->about = $this->input->post('about');
//insert information into the saint table
$this->db->insert('saint_table', $this);
}
public function set_of_region($newSaintID)
{
$this->saintID = $newSaintID;
$this->ofRegion = $this->input->post('ofRegion');
$this->db->insert('saint_of_region', $this);
}
Controller Function
public function saint_input()
{
//Check if user is logged in, if they are not, send them to the login screen
if($this->session->userdata('logged_in') == FALSE)
{
redirect('base/');
}
$this->load->library('form_validation');
//load Saint model and get the nation list
$this->load->model('saint_model');
//Load the nation list
$data['nationList'] = $this->saint_model->get_nations();
if($this->form_validation->run('saint_input')==FALSE)
{
$this->load->view('std/top');
$this->load->view('forms/saint_input', $data);
$this->load->view('std/bottom');
}
else
{
//generate saintID
$newSaintID = $this->saint_model->get_largest_saintID();
$newSaintID++;
$this->saint_model->input_saint($newSaintID);
//if specified, record the ofRegion
if($this->input->post('ofRegion') != NULL)
{
$this->saint_model->set_of_region($newSaintID);
}
//Send the user to this saint's single view page for review
redirect('base/display_one_saint/'.$newSaintID);
}
}
Thank you very much for your time and work!
That's because you're using $this as an array to store data before inserting it. $this is a reference to the object as a whole and any properties that you set on it will persist until they are unset. One solution is to change to an array for the insert() function as below:
public function set_of_region($newSaintID)
{
$ins_arr['saintID'] = $newSaintID;
$ins_arr['ofRegion'] = $this->input->post('ofRegion');
$this->db->insert('saint_of_region', $ins_arr);
}

Categories