I'm trying to convert code I wrote for my Controller to work as a model so that I can pull the information into a Blade.
Basically I'm taking random percents from a table in my database labeled "margins" and multiplying it by the cost of multiple items. I then need to do something like
#foreach($item_cost as $ic)
Item Name: {{ $ic->name }} Cost: {{ $ic->cost }}
#endforeach
where it pulls the item name from the "items" table and then multiplies a base cost by the margin in the "margins" table.
public function drug_margins()
{
$locations = Locations::inRandomOrder()->get()->first();
$drugs = Drugs::inRandomOrder()->get()->first();
$margins = Margins::inRandomOrder()->get()->first();
$add = $locations->margin*$drugs->base_value*$margins->percent;
$cost = $add+$drugs->base_value;
return "<h2>Trismegistus Drug Cost Randomizer</h2><br>Drug Name: " . $drugs->name . "<br>" . "Location: " . $locations->name . "<br>" . "Location Margin: " . $locations->margin . "<br>" . "Margin: " . $margins->percent . "<br>" . "Drug Base Value: " . $drugs->base_value . "<br>" . "New Cost: " . $cost . "<br>";
}
If this isn't make sense please let me know so I can clarify.
TIA!
I've tried using the information from the first answer but it's not working 100%. The cost is changing accordingly however the "Drug Name" is staying the same no matter what.
Here is my model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Drugs extends Model
{
//
protected $table = 'drugs';
public function user_data()
{
return $this->belongsTo('user_data', 'TableID', 'id');
}
public function getCostAttribute()
{
$locations = Locations::inRandomOrder()->get()->first();
$drugs = Drugs::inRandomOrder()->get()->first();
// $drugs = Drugs::find(1)->get()->first();
$margins = Margins::inRandomOrder()->get()->first();
$add = $locations->margin*$drugs->base_value*$margins->percent;
$cost = $add+$drugs->base_value;
//$cost = array('name' => $drugs->name, 'base_value' => $drugs- >base_value, 'cst' => $cst); // Presents array but can't get it to work as variables in view
return $cost;
}
}
and here is my Controller:
public function drug_margins()
{
$drugs = Drugs::inRandomOrder()->first();
$drugs = $drugs->cost;
dd($drugs); // Testing Phase
// return view('test.test', compact('drugs'));
}
Can anyone see what I'm doing wrong. Again the drug costs are changing properly now but the drug name stays as the first drug which is Aspirin.
Thanks again!
You can define an accessor in the model as:
public function getCostAttribute()
{
// write your logic here
return $cost;
}
And then you can use it as:
{{ $model->cost }}
Related
I'm new in Laravel. I attached my code whenever I update the form it gives same error. Please check my code throughly and let me know where is the error.
public function updateCategory(Request $request) {
$catname = $request->catname;
if($catimg = $request->hasFile('updatecatimg')) {
File::cleanDirectory(public_path().'/images/'.$catname);
$catimg = $request->file('updatecatimg');
$catimgnm = $catimg->getClientOriginalName();
$storeTo = public_path() . '/images/' . $catname;
File::makeDirectory($storeTo, $mode = 0777, true, true);
$catimg->move($storeTo, $catimgnm);
}
Category::where('cat_id', $request->catid)->update(['cat_name' => $catname, 'cat_img' => $catimgnm, 'status' => $request->status]);
return back();
}
Category Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AddCategory extends Model
{
protected $table = 'cms_category';
protected $primaryKey = 'cat_id';
}
Folder
DB
Error
please help me...
Here is your updated answer. Category::findOrFail() will find the category object, using it, we can update specific field only and use save() function to update the object.
public function updateCategory(Request $request)
{
$catId = $request->catid;
$category = Category::findOrFail($catId);
$oldCategory = $category->cat_name;
rename(public_path() . '/images/' . $oldCategory, public_path() . '/images/' . $request->catname);
$category->cat_name = $request->catname;
if ($request->hasFile('updatecatimg')) {
File::cleanDirectory(public_path() . '/images/' . $request->catname);
$catImg = $request->file('updatecatimg');
$category->cat_img = $catImg->getClientOriginalName();
$storeTo = public_path() . '/images/' . $request->catname;
File::makeDirectory($storeTo, $mode = 0777, true, true);
$catImg->move($storeTo, $request->catname);
}
$category->save();
return back();
}
You should try this code.
This is your edit file
<input type="hidden" name="old_image" id="old_image"
value="{{isset($contact->cat_img)?$contact->cat_img:''}}">
After:
use File;
public function updateCategory(Request $request) {
if ($request->hasFile('updatecatimg')){
$image_path = public_path('/images/'.$request->old_image);
if(File::exists($image_path)){
unlink($image_path);
}
$file = $request->file('updatecatimg');
$catimgnm = $file->getClientOriginalName();
$destinationPath = public_path('/images/');
$file->move($destinationPath, $catimgnm );
$contact = "YOUR MODEL NAME"::find($request->cat_id);
$contact->cat_img =$catimgnm ;
$contact->save();
}
}
I hope this code is working in your Controllers.
Say if I defined a route GET /user/{user_id}/post/{post_id}. How do I get the un-substitute route in middleware? i.e. if the request is GET /usr/123/post/456, is there a pre-defined function that can get me /user/{user_id}/post/{post_id}?
I am currently using following snippet
$urlParam = $request->route()[2];
if (isset($urlParam) && count($urlParam)) {
$urlPath = substr(str_replace(
array_map(function($item) { return "/" . $item . "/"; }, array_values($urlParam)),
array_map(function($item) { return "/{" . $item . "}/"; }, array_keys($urlParam)),
"/" . $request->path() . "/"), 1, -1);
}
return $urlPath;
but as you can see this is not bug-free, if both user_id & post_id are the same, above snippet will not generate right result.
In Laravel
If you wan to get the same route URI you can use
$request->route()->uri();
This will return user/{user_id}/post/{post_id}
In Lumen
$segments = $request->segments();
foreach ($request->route()[2] as $parameter => $value) {
$segment_index = array_search($value, $request->segments());
$segments[$segment_index] = "{{$parameter}}";
}
$segments = implode('/', $segments);
dd($segments);
And the result will be user/{user_id}/post/{post_id}
This is the data that I have in database
This is what I want to make in the view.blade.php
What I want to do is I want to get the data from the database, if the data inside the column is 1, I want to get the column name as you can see in image 2, but there could be more than 1 column name because the column with data can be column A,B,C... etc.. and I want to show the student name and the subject (a,b,c... etc) if the data in it is '1' in the view. I stuck on how to get all those subject A,B,C.. this is the code that I have written, but it is incomplete because I don't know what to add on it to make it as what I have mentioned above. Hopefully, someone can help me. Thanks in advance
if($row->'A'=='1'){i dont know what should i put here so that i cant get the column name 'A' and print it in view.blade.php}
Assuming your table in database is student_details, create an eloquent model StudentDetail inside app/models/StudentDetail.php :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class StudentDetail extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'student_details';
/**
* Get subjects in the view
*
* #return string
*/
public function getSubjects()
{
$subjects = [];
$subjects[] = $this->A == 1 ? 'A' : null;
$subjects[] = $this->B == 1 ? 'B' : null;
$subjects[] = $this->C == 1 ? 'C' : null;
$subjects = array_filter($subjects);
return implode(',', $subjects);
}
}
Then you can retrieve data in your controller :
public function view()
{
$studentDetails = StudentDetail::get();
return view('view.path', compact('studentDetails'));
}
And inside view you can do :
#foreach($studentDetails as $detail)
{{ $detail->name }} : {{ $detail->getSubjects() }}
#endforeach
You can use appended property as well, I have not used that because appended property is added every-time when model is instantiated. I believe having it in a function makes it flexible to use as and when needed.
Okay i tried it bit different way it's not proper but it will give you desired output you want :-
Route::get('/test',function(){
$query = TestTable::all();
$calculateData = [];
foreach ($query as $key){
$subjects = '';
if($key->A === 1){
$subjects .= 'A';
}
if($key->B === 1){
$subjects .= 'B';
}
if($key->C === 1){
$subjects .= 'C';
}
$calculateData[] = [$key->name,$subjects];
}
foreach ($calculateData as $key){
dump("NAME : " . $key[0]."Subject : " . $key[1]);
}
dd("STOP");
})->name('test');
return Store::whereRaw('status = 1 AND ' . 'pay_status = 1 AND ' . $conditions[0])
->storeBooks()
->whereRaw('status = 1 AND ' . $conditions[1])
->search($request->input('search'), null, true)
->simplePaginate(20)
->makeHidden(['description', 'publisher', 'edition', 'mobile', 'cat_title', 'city_name']);
Hi, I have an store table and this table has some book in store_books table.
i want to search in store books where store has status 1.
I wrote above code but not work.
anyone can help me? Please!
Thanks
You can try this
In your Store model
public function books()
{
return $this->hasMany("App\StoreBooks",'store_id');
}
In your controller's function
$results = [];
$stores = Store::where('status',1)->get();
foreach($stores as $store)
{
$books = $stores->books;
foreach($books as $book)
{
$results[] = $book;
}
}
return $results;
I built this method following the the tagged() method from blog module
public function genres($genre = null)
{
$this->db->order_by('name', 'ASC');
$result = $this->db->get('keywords');
$genres = $result->result();
if($genre)
{
$this->load->model('genres_m');
// decode encoded cyrillic characters
$genre = rawurldecode($genre) OR redirect('generos');
$time[] = time();
// Count total blog posts and work out how many pages exist
$pagination = create_pagination(lang('ebooks:routes:genres') . '/' . $genre, $this->genres_m->count_genres_by($genre, array('entry_active' => 1)), NULL, 4);
$time[] = time();
// Get the current page of blog posts
$books = $this->genres_m
->limit($pagination['per_page'])
->order_by('info_title', 'ASC')
->get_genres_by($genre, array('entry_active' => 1));
$time[] = time();
foreach ($books AS &$book)
{
$book->books_info_genre = Keywords::get($book->books_info_genre, 'blog/tagged');
$book->url = site_url(lang('ebooks:routes:ebook') . '/' . $book->info_title . '/' . $book->id);
}
$time[] = time();
// Set meta description based on post titles
//$meta = $this->_posts_metadata($books);
$name = str_replace('-', ' ', $genre);
// Build the page
$this->template
->title($this->_template_title(lang('ebooks:of').' '.$name))
->set_metadata('description', $this->_template_title(lang('ebooks:of').' '.$name))
->set_metadata('keywords', $this->_template_title(lang('ebooks:of').' '.$name))
->set('genres', $genres)
->set('books', $books)
->set('genre', $genre)
->set('time', $time)
->set('pagination', $pagination)
->build('genres-list');
}
else
{
$this->template->title($this->_template_title(lang('ebooks:genres_by')))
->set_metadata('description', $this->_template_title(lang('ebooks:genres_by')))
->set_metadata('keywords', $this->_template_title(lang('ebooks:genres_by')))
->set('genres', $genres)
->build('genres-list');
}
}
And, this is the model:
public function count_genres_by($genre, $params)
{
return $this->db->select('*')
->from('downloads_books_book_info')
->join('keywords_applied', 'keywords_applied.hash = downloads_books_book_info.books_info_genre')
->join('keywords', 'keywords.id = keywords_applied.keyword_id')
->where('keywords.name', str_replace('-', ' ', $genre))
->where($params)
->count_all_results();
}
public function get_genres_by($genre, $params)
{
return $this->db->select('*')
->from('downloads_books_book_info')
->join('keywords_applied', 'keywords_applied.hash = downloads_books_book_info.books_info_genre')
->join('keywords', 'keywords.id = keywords_applied.keyword_id')
->where('keywords.name', str_replace('-', ' ', $genre))
->where($params)
->get()
->result();
}
As you can see in the first part of code, I got the time() four times, giving the delays:
18:49 - 19:03 - 19:41 - 19:41
I have a DB with about 5K entries. How can I optimize this code?
You can use 2.2.0-beta1 and take advantage of the Search system, which will store all keywords as text and knock out a few joins for your queries.
Otherwise you can build your own index table using blog events, which will store keywords next to blog id's.
The main problem is that your are running an SQL query on EVERY single returned item, whilst it would be quicker to work out all the keywords in one go. Even a SQL sub-query would be slightly quicker.