How Access Database Values Using Array In Laravel - php

I am creating a web site. So , I have stored data in the database. Now I want to view data from two different tables. Then I tried a method like below. But , it gives me this error -
Trying to get property 'firstname' of non-object (View: D:\wamp64\www\cheapfares\resources\views\invoices\des.blade.php)
But , clearly firstname is in the database table.
How can I Fix this ??
Controller page. ( InvoicesController.blade.php )
public function userinvoice($terms = '',$invoiceNo = '')
{
$invoice = Invoice::where('invoicereference', $invoiceNo)->get()->first();
$tr = DB::table('termsandconditions')
->where('topic', $terms)->get()->first();
$twoar = [];
$twoar['inv'] = $invoice;
$twoar['trms'] = $tr;
return view('invoices.des', ['twoar' => $twoar]);
}
View page. ( des.blade.php )
{{$twoar['inv']->firstname}}
{{$twoar['trms']->topic}}
Route.
Route::get('/invoice/adminuser-invoice/{invoiceno}', [
'uses' => 'InvoicesController#adminuserinvoice',
'as' => 'invoice.adminuser'
]);

Although casting the response to Array might be a suitable solution, the cause of your exception most likely lies in not having a valid entry in the database.
You can improve your code like this to mitigate that:
public function userinvoice($terms, $invoiceNo)
{
// Load invoice, or throw ModelNotFoundException/404 without valid entries.
$invoice = Invoice::where('invoicereference', $invoiceNo)->firstOrFail();
// load the terms.
$terms = DB::table('termsandconditions')
->where('topic', $terms)->first();
return view('invoices.des', compact('invoice', 'terms'));
}
In this example I made $terms and $invoiceNo obligated arguments in the route. To ensure the query will provide proper results. In addition an Invoice entry is now required with firstOrFail(), the terms is optional. Instead of assigning both variables to an array, I'm sending them both to the view so you can assert their value properly without cluttering using array key access.
Your view:
{{$invoice->firstname}}
{{$terms->topic}}

Try this below code:
public function userinvoice($terms = '',$invoiceNo = '')
{
$invoice = Invoice::where('invoicereference', $invoiceNo)->get()->first();
$tr = DB::table('termsandconditions')
->where('topic', $terms)->get()->first();
return view('invoices.des', ['tr'=>$tr,'invoice'=>$invoice]); //Directly pass the mulitple values into the view
}
And your view page like this:
{{$invoice->firstname}}
{{$tr->topic}}
Its may help for you friend.

Related

Database data field check before Data insertion

I have a data coming from the HTML Page. And i want to check whether the date and the place values already exists. If they exists, it should throw an error saying Data is already present, if those date and place data is not there it should allow the user to save it.
Here is the code which i have written to save it,
public function StoreSampling(Request $request)
{
$date = Carbon::createFromFormat('d-m-Y', $request->input('date'))->format('Y-m-d');
$doctorname = Input::get('doctorselected');
$product = Input::get('product');
$product= implode(',', $product);
$quantity = Input::get('qty');
$quantity =implode(',',$quantity);
$representativeid = Input::get('representativeid');
//Store all the parameters.
$samplingOrder = new SamplingOrder();
$samplingOrder->date = $date;
$samplingOrder->doctorselected = $doctorname;
$samplingOrder->products = $product;
$samplingOrder->quantity = $quantity;
$samplingOrder->representativeid = $representativeid;
$samplingOrder->save();
return redirect()->back()->with('success',true);
}
I searched some of the Stack over flow pages. And came across finding the existence through the ID And here is the sample,
$count = DB::table('teammembersall')
->where('TeamId', $teamNameSelectBoxInTeamMembers)
->where('UserId', $userNameSelectBoxInTeamMembers)
->count();
if ($count > 0){
// This user already in a team
//send error message
} else {
DB::table('teammembersall')->insert($data);
}
But i want to compare the date and the place. And if they are not present, i want to let the user to save it. Basically trying to stop the duplicate entries.
Please help me with this.
There are very good helper functions for this called firstOrNew and firstOrCreate, the latter will directly create it, while the first one you will need to explicitly call save. So I would go with the following:
$order = SamplingOrder::firstOrNew([
'date' => $date,
'place' => $place
], [
'doctorname' => Input::get('doctorselected'),
'product' => implode(',', Input::get('product')),
'quantity' => implode(',',Input::get('qty')),
'representativeid' => Input::get('representativeid')
]);
if($order->exists()) {
// throw error
return;
}
$order->save();
// success
You need to modify your query to something like this:
$userAlreadyInTeam = SamplingOrder::where('date', $date)
->where('place', $place) // I'm not sure what the attribute name is for this as not mentioned in question
// any other conditions
->exists();
if (userAlreadyInTeam) {
// Handle error
} else {
// Create
}
You do not need to use count() as your only trying to determine existence.
Also consider adding a multi column unique attribute to your database, to guarantee that you don't have a member with the same data and place.
The best way is to use the laravel unique validation on multiple columns. Take a look at this.
I'm presuming that id is your primary key and in the sampling_orders table. The validation rule looks like this:
'date' => ['unique:sampling_orders,date,'.$date.',NULL,id,place,'.$place]
p.s: I do not see any place input in your StoreSampling()

how do i fetch item from database and display in my views in laravel

i need the code that will enable me fetch an entire table from the database and load it to my view. and also to the code that will display the item in my views
my controller:
public function index()
{
if(Auth::user()->usertype=='Admin')
{
$categories_count = Categories::count();
$news_count = News::count();
$published_news = News::where('status', 1)->count();
$unpublished_news = News::where('status', 0)->count();
$slider_news = News::where('slider_news', 'yes')->count();
$slidsder_news = News::where('slider_news', 'yes')->count();
$featured_news = News::where('featured_news', 'yes')->count();
$editor = User::where('usertype', 'Editor')->count();
}
else
{
$user_id=Auth::user()->id;
$news_count = News::where(['user_id' => $user_id])->count();
$published_news = News::where(['user_id' => $user_id, 'status' => '1'])->count();
$unpublished_news = News::where(['user_id' => $user_id, 'status' => '0'])->count();
}
return view('admin.pages.dashboard',compact('categories_count','news_count','published_news','unpublished_news','slider_news','featured_news','editor'));
}
You can simply do
Model::all();
To get all the data for that model/table. I would recommend paginating this if you have large data sets like so:
Model::all()->paginate(20);
See pagination here.
Once you have this assigned to a variable, as you already have done, you can pass it into your compact.
Within your view, it's always worth checking the collection isn't empty before attempting to loop over:
#if ($exampleItems->isNotEmpty())
and then you can continue to loop over the collection:
#foreach ($exampleItems as $exampleItem)
I recommend learning the basics using various tutorials such as Laracasts because if I've understood your request, this is fairly basic.

Codeigniter 3 model function no return variable

I'm making a project where a user can publish/post their own stories and read others' stories. Very simple.
This is my controller method named publish:
public function published()
{
$story = array('author' => $this->session->userdata('username'),
'title' => $this->input->post('title'),
'synopsis' => $this->input->post('synopsis'));
$new_storyid = $this->story_model->new_story($story);
if($new_storyid != NULL)
{
$genre = $this->input->post('genre');
for($temp=0;$temp<count($genre);$temp++)
{
$genres[$temp] = array('story_id' => $new_storyid,
'story_genre_name' => $genre[$temp]);
}
$insert_genre = $this->story_model->new_story_genre($genres);
$tag = $this->input->post('tags');
for($temp=0;$temp<count($tag);$temp++)
{
$tags[$temp] = array('story_id' => $new_storyid,
'story_tag_name' => $tag[$temp]);
}
$content_warning = $this->input->post('content_warning');
for($temp=0;$temp<count($content_warning);$temp++)
{
$content_warnings[$temp] = array('story_id' => $new_storyid,
'story_content_warning_name' => $content_warning[$temp]);
}
//$chapter = array('story_id' => $new_storyid,
//'chapter_number' => 1, 'chapter_title' => $this->input->post('chapter_title'),
//'chapter_content' => $this->input->post('chapter_content'),
//'chapter_number' => 1, 'date_added' => mdate('%Y-%m-%d %h-%i-%s',time()));
//$result = $this->story_model->add_chapter($chapter);
//if($result){
//redirect('account/userprofile_published_stories');}
}
}
This is my model methods for the above controller method:
public function new_story($story)
{
$this->db->select('user_id');
$query = $this->db->get_where('users',array('username' => $story['author']))->result();
foreach($query as $row)
{ $userid = $row->user_id; }
$publish = array('user_id' => $userid,
'story_title' => $story['title'],
'synopsis' => $story['synopsis']);
$this->db->insert('story',$publish);
return $this->db->insert_id();
}
public function new_story_genre($genre)
{
foreach($genre as $row)
{
$this->db->insert('story_genre', $row);}
}
public function add_chapter($chapter){
$this->db->where('story_id', $chapter['story_id']);
return $this->db->insert('chapters', $chapter);
}
I haven't added the other 2 functions for my tags and content warning inserts because i am confused right now. It all works fine, my genre is inserted.
My tables looks like this:
Story tables
In inserting a story in my above method, the first thing i do is insert a new story row in my story table and returns the new_storyid variable.
after that with the new storyid i add the genre,tags,content warning then the chapters.
My question is, what should i return in my methods for inserting the genre,tags,contentwarning?
I forgot this part because every model method ive written so far always returns a variable i needed in my controller. My first thought was to return a TRUE/FALSE variable if insert is successful/fail but barring special circumstances since ive already processed the data its 100% sure to insert successfully. Should i be returning TRUE/FALSE and adding an if statement like:
if($insert_genre){
//insert tags here
if($insert_tags){
//insert content warning here
if($insert_content_warning){
//insert chapters here
//redirect to view here
}
}
}
Or can i just not return anything? and if so, is this a proper/right way?
EDIT: I forgot to mention i haven't yet added form_validation rules before all the inserts. So my function will be nested in multiple if statements.
I just edited my model method:
public function new_story_genre($genre){
$inserted = 0;
foreach($genre as $row){
$this->db->insert('story_genre', $row);
$inserted += $this->db->affected_rows();}
if($inserted == count($genre)){
return TRUE;}else{ return FALSE; }
}
Above compares the number of inserted rows with the number of rows passed into the method. Everytime a row is inserted it adds 1 to the inserted variable. So if my controller passes 3 rows into the method, the inserted variable should also be 3 for a successful insert.
I think you are correct in always returning something. Errors can and do happen for whatever reason, and its a good idea to account for them even if you already validated your data (you never know). Coding practices suggest that more than a couple of nested ifs is bad practice. A personal preference of mine is to check for failure rather than success all the way down the chain until the last lines of the function (if it got that far than everything is good to go).
A scheme like this I usually use:
public function something() {
if (!$insert_genre) {
// add flash error message
// redirect to controller
}
if (!$insert_tags) {
// add flash error message
// redirect to controller
}
if (!$insert_content_warning) {
// add flash error message
// redirect to controller
}
// yay, something went right!
}
In this kindof circumstance it is very procedural. The most important conditions should be first, and if C depends on A, then A should be the first condition.
Unrelated:
It is hard to follow some of your text here, but it also seems like you should look into how you are doing the genres. If the entered genre already exists in the database do you really need to add it? Shouldn't you just use a relationship there storing the id in the main table and joining when displaying?

How to apply PHP function to a column returned from CakePHP query

In my controller I am retrieving records from my institutions table with the following fields
$params = array(
'fields' => array(
'Institution.id',
'Institution.name',
'Institution.about',
'Institution.picture'),
);
$institutions = $this->Institution->find('all',$params);
How can I prefix each 'Institution.picture' field with the full URL address, 'Institution.picture' itself only holds the name of the file.
I would also like to perform html_entity_decode() on each 'Institution.about' value from the returned set.
I know how to do this only without the framework if I make custom queries from scratch, then I would iterate each row and apply PHP functions to the field of interest. But is there a place in CakePHP (find or paginator) that I can specify such PHP manipulation on each field value from the returned set?
NOTE: I don't like to do this in the View, as I want to output it as json directly
You can define a virtualField for model:
public $virtualFields = array('image_url' => "CONCAT('/img/', Institution.picture)");
$params = array(
'fields' => array(
'Institution.id',
'Institution.name',
'Institution.about',
'Institution.picture',
'Institution.image_url'),
);
$institutions = $this->Institution->find('all',$params);
Unfortunaly MySQL doesn't have a function to decode HTML entities. You may utilize an afterFind() callback instead of virtualField. This lets you to decode entities as well as add a prefix.
CakePHP is php
Just iterate over the array and prepare it however you want:
$institutions = $this->Institution->find('all',$params);
$prefix = '/img/'; // <- define this
foreach ($institutions as &$row) {
$row['Institution']['about'] = html_entity_decode($row['Institution']['about']);
$row['Institution']['picture'] = $prefix . $row['Institution']['picture'];
}
If this is always required it can be applied to all finds via an afterFind method in the institution class.
I think you should do it in the View. See this example.
Hash::map can be very useful here. By specifying path you can only modify slices of the set.

CakePHP: Why am I unable to update record with set() or save()?

I've been trying all night to update a record like this:
$r = $this->Question->read(NULL, $question['Question']['id']);
debug($r);// This is a complete Question array
$this->Question->set('status', 'version');
$s = $this->Question->save();
//$s = $this->Question->save($r['Question']);//this also doesn't work
debug($s); // = False every time!! Why??
exit;
The two comments show variations I've tried but didn't work either.
#Dipesh:
$this->data = $this->Question->read(NULL, $question['Question']['id']);
$this->Question->status = 'version';
$s = $this->Question->save($this->data);
debug($s);
exit;
#Dipesh II:
$this->request->data = $this->Question->read(NULL, $question['Question']['id']);
debug($this->data);
//$this->Question->status = 'version';
$this->request->data['Question']['status'] = 'version';
$s = $this->Question->save($this->request->data);
//$s = $this->Question->save($r['Question']);
debug($s);
exit;
#Dipesh III:
(removed)
cakePHP provide a method called set() in both Models::set() as well as in Controller::set();
About Controller::set()
This method is used to set variables for view level from any of the controller method. For example fetching records and from models and setting them for views to display it to clients, like this
$data = $this->{ModelName}->find('first');
$this->set('dataForView',$data) // now you can access $data in your view as $dataForView
About Model::set()
This method is used to set data upon a model, the format of the array that will be passed must be same as that used in Model::save() method i.e. like this
$dataFormModel = array('ModelName'=>array('col_name'=>$colValue));
$this->{ModelName}->set($dataForModel);
Model::set() will accept its parameter only in this format, once successfully set you can do following
validate this data against the validation rules specified in model directly like this
$isValid = $this->ModelName->validate();
save/update data by calling Model::save()
Use $this->data instead of $r
Example
$this->data = $this->Question->read(NULL, $question['Question']['id']);
$this->set is used to set variable value and pass it to view so view can access it where as $this->data represent the data to be stored in database.
If You're using Cake 2.0 then replace $this->data which is read only in Cake 2.0 to $this->request->data.
It's not very "automagical" but I was able to get this working like this:
$set_perm_id = 42;//who cares
$data = array(
'Question'=> array(
'id'=> $question['Question']['id'],
'perm_id'=> $set_perm_id,
'status'=>'version'
)
);
$s=$this->Question->save($data);
Basically I'm just building the data array manually. If anyone knows why this works instead of what I was doing before, I'd love to hear it.
Just try these lines..
$this->Question->id = $question['Question']['id'];
$this->Question->set('status','version');
$this->Question->save();
OR
$aUpdate["id"] = $question['Question']['id'];
$aUpdate["status"] = "version";
$this->Question->save($aUpdate);

Categories