I am developing a project in Laravel 5.4. I want to write a select, insert and update query in my model that should work for any table in database. I used to do this is Codeigniter and work fine there, but I don't know how to use it in Laravel.
Following is the code from a model file in Codeigniter
class General_Model extends CI_Model {
public function fetch_CoustomQuery($sql){
$query = $this->db->query($sql);
return $query->result();
}
public function create_record($data, $tbl)
{
$this->db->set($data);
$this->db->insert($tbl);
return ($this->db->affected_rows() != 1) ? FALSE : TRUE;
}
public function update_record($data, $tbl, $wher)
{
$this->db->where($wher);
$this->db->set($data);
$this->db->update($tbl);
}
public function delete_record($tbl, $wher)
{
$this->db->where($wher);
$this->db->delete($tbl);
}
}
It was very easy in Codeigniter. I only need to pass the parameters and worked fine. I want to write same queries in my model in Laravel. Please help
I would strongly recommend reading the documentation but the methods are as simple as:
GeneralModel::create(["num" => 1, "name" => 2]);
GeneralModel::where("num", ">", 2)->update(["num" => 1]);
GeneralModel::where("num", ">", 2)->delete();
There is no need to put these methods on the models.
if you really want something like that then you can have function there that accepts models as parameter:
public function create_record($model,$data)
{
$model::create($data);
}
where in the controller you can do something like
$model = App\Fruit; // lets say fruit is a model you have
GeneralModel::create_record($model,$data);
but why not just go straight with it like:
$var = App\Fruit::create($data);
this is redundant .. for each model have a way to fetch , insert , update or delete records from their perspective table .. i suggest you read more documentation about Laravel Eloquent
Related
I wrote the following 'insert code' in a way that I can use it many times. So without writing the table name in the model I could write the table name in the controller.
model function
function insertTable($table, $data) {
$this->db->insert($table, $data);
return $this->db->insert_id();
}
controller instruction
$insert = $this->Model_Action->insertTable('student',$student_data)
But I want to do the same in the following code as well. Is there a way to replace the p_id as $id?
Model
function delete_by_id($id)
{
$this->db->where('p_id', $id);
$this->db->delete('parent');
}
Controller
public function student_delete($id)
{
$this->load->model('Model_Action');
$this->Model_Action->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
Yes you can. your model
function delete_by_id($column_name, $id){
$this->db->where($column_name, $id);
$this->db->delete('parent');
}
then use it in controller's student_delete methos like
$this->Model_Action->delete_by_id('p_id', $id);
If you want delete 'student' table row by ID, you can use to below code.
function delete_by_id($id)
{
$this->db->delete('student', array('id' => $id));
}
If you want delete different table row by ID:
function delete_by_id($table, $id)
{
$this->db->delete($table, array('id' => $id));
}
Well, you should use codeigniter Core Classes.
In folder hierarchy, there is a folder named core in which you can make parent controller and model.
You can make all functions of model which we are using in almost all models like for create, update, delete, read records in this parent model and inherit our app models from this model.
In our Controller, we just need to get model name and use these functions.
Note: I am using same way since 2018.
You can define Table_name in model for reusable insert , delete, edit methods.
You can use where conditions usig condition wise.
Ex.
function get($id='',$name='')
{
if($id >0)
{
$this->db->where('id',$id);
}
}
Controller:
Write required database table name to variable $table in controller. And pass the variable $table to model.
Model:
function insertTable($table, $data) {
$this->db->insert($table, $data);
return $this->db->insert_id();
}
This is my Report Model
protected $fillable = [
'site_url',
'reciepients',
'monthly_email_date'
];
public function site()
{
return $this->belongsTo('App\Site');
}
This is my Site Model
public function report()
{
return $this->hasMany('App\Report');
}
This is my ReportController
public function showSpecificSite($site_name)
{
$records = DB::table('reports')
->select('email_date','url','recipient')
->whereHas('sites', function($query){
$query->where('site_name',$site_name);
})
->get();
return view('newsite')->with('records',$records)
->with('site_name',$site_name);
}
My Controller is not yet working as well.
The thing is I would like to copy all the three files from sites table to reports table.
Is it possible in insertInto ?
My code on ReportController shows you that I'm selecting data from reports table but I am the one who puts data to reports table to see the output but it is not yet working because of the it cant reach out the value of site_name even though I already put a relationship between the two tables.
You're not actually using Eloquent in your controller you're just using the Query Builder (DB). This will mean that you don't have access to anything from your Eloquent models.
Try:
$records = \App\Report::whereHas('site', function($query) use($site_name) {
$query->where('site_name', $site_name);
})->get(['id', 'email_date', 'url', 'recipient']);
I've added id to the list of columns as I'm pretty sure you'll need that to use whereHas.
NB to use a variable from the parent scope inside a closure you need to pass it in using use().
I'm using CodeIgniter to build a website, and I want to show a list of construction projects from a database table, which we will simply call project_table. For each project I also have an address, stored in another table, address_table, each address has a project_id, which links it to a project.
I have made a function, get_projects, in my projects model, which is used to get the project information and pass it to the project view, like such:
public function index() {
$data['projects'] = $this->project_model->get_projects();
$data['title'] = 'Ejendomme';
$this->load->view('templates/header', $data);
$this->load->view('projects/index', $data);
$this->load->view('templates/footer');
}
My question is how I get the addresses read, linked to the correct projects, and shown. I suppose I could make a function which is called from the view, which loads the address based on project_id, but as I understand it, this is really bad practice. Is there a way to call a get_address function from the controller, and pass it on to the view, without losing track of which address belongs to which project?
Update:
Per request here is the function get_project(), which gets the project information from the database. I have considered calling a get_address() function inside this, but I am not sure how I would return the addresses from the function.
// Function to read all projects from database
public function get_projects() {
$query = $this->db->get('project_table');
return $query->result_array();
}
Was more useful if you've posted the get_projects method from models. Anyway, the trick is to make use of Model-View-Controller(MVC) architecture, therefore you put into the model the selection from database.
Here is an example with a method to extract your data from those two tables:
public function get_projects()
{
//for standard mySQL
//select only the db fields that you need
$query = "SELECT pt.*, at.* FROM project_table as pt, address_table as at WHERE pt.project_id = at.project_id";
$db_result = $this->db->query($query);
$result_object = $db_result->result();
/*
here you can add a check for the result (for instance to check if the return is not empty)
*/
return $result_object;
}
Now parse the result to a view and play from there with the data.
Joining the ideas in the previous answers, you could use the query builder (using CI 3 name) to join the two tables and return all the information you need from that method in the model:
public function get_projects() {
$this->db->from('project_table');
$this->db->join('adress_table', 'adress_table.project_id', 'project_table.id');
return $this->db->get()->result_array();
}
You can learn more about the QueryBuilder Class at the documentation.
Ideally you want to keep all your database queries in the model. You can call other functions in your model by using $this->function_name().
I believe this will achieve what you are after (these go in your model):
// Function to read all projects from database
public function get_projects() {
$results = $this->db->get('ed_projects')->result();
foreach($results as $r) {
$r->address = $this->get_address($r->id);
}
return $results;
}
// Function to read addresses for a $project_id
private function get_address($project_id) {
return $this->db->from('project_address_table')
->where('project_id', $project_id)
->get()->result();
}
I would also recommend using the codeigniter active record class (http://www.codeigniter.com/user_guide/database/active_record.html) for doing easy database queries like this as it makes it a lot easier to see what your query is doing
Please indicate me where i can add a customized function in Laravel framework or is there something missing in the installation?
i'm trying to use the function
public function select($query, $bindings = array())
{
return $this->run($query, $bindings, function($me, $query, $bindings)
{
if ($me->pretending()) return array();
// For select statements, we'll simply execute the query and return an array
// of the database result set. Each element in the array will be a single
// row from the database table, and will either be an array or objects.
$statement = $me->getPdo()->prepare($query);
$statement->execute($me->prepareBindings($bindings));
return $statement->fetchAll($me->getFetchMode());
});
}
from the tutorial http://fideloper.com/laravel-raw-queries
but i cannot find where to modify my existing Laravel framework.
I need to run a query have inner join from 3 tables and collect the data and post it in grid. I need to modify in Laravel framework and create a function of my own.
Please help.
Thank you.
yes so in your controllers you have method that correspond to a route.
So choose the method corresponding to your route and call this function in that method.
For example in your HomeController.php
Class HomeController extends BaseController {
public function index() {
$yourData = DB::raw('your query');
// if you want to inject it in your view.
return View::make('yourtemplatename', ['yourdata' => $yourData]);
}
}
And in your file routes.php
route::get('/', 'HomeController#index');
But there is prettiest way to do queries with Eloquent.
Check the documentation for that.Your query is not as hard as it looks it a forest of join.
I use models that extend a generic_model, which in turn extends Eloquent (so that I have several crud methods I use already set to be inherited).
A lot of the tables I use invoke soft delete, which needs a WHERE clause of...
WHERE deleted = 0
Is there a way to make Laravel behave in such a way that this WHERE clause is automatically included in all queries and all queries to objects that are related to one another?
e.g.
pages where id = 5 and deleted = 0
and then...
images where page_id = 5 and deleted = 0
if you're using laravel 3 this is what you needs
on your model
public function query()
{
$query = parent::query();
$query->where('deleted','=','0');
return $query;
}
if you're using laravel 4 just change the method query for newQuery
public function newQuery()
{
$query = parent::newQuery();
$query->where('deleted','=','0');
return $query;
}
reference
In relationships you can add the where_clause in your return:
public function pages()
{
return $this->has_many('Page')->where_deleted(0);
}
In your Model, you could add something like:
public static function active()
{
return self::where_delete(0)->get();
}
to use Page::active() instead of Page::all()
(Or you can remove the ->get() from the function in the model, so you can still further modify your query (Page::active()->order_by('name'))