customized function raw query in Laravel framework - php

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.

Related

Laravel - 404 | Not Found upon "/{id}" entry

I am getting a "404 | Not Found" error when i try to access a specific item from my database. The items with the specific ID's do exist in the database, but i am not even sure if that even has any influence on the problem.
My routing looks likes this:
Route::prefix('departments')->group(function() {
Route::get('/{id}', [DepartmentController::class, 'showDepartment']);
});
And the related controller looks like this:
public function showDepartment() {
return '';
}
}
I haven't yet finished the function. I just wanted to check if the routing even worked by returning an empty string.
So what am i doing wrong? Is it the routing or the controller?
According to the Laravel documentation, you have to define the parameter in the route then use it in the controller as a parameter.
in your controller:
public function showDepartment($id) {
return 'Hello';
}
The id is not bound to any model to fetch from the database to do that you can use Laravel route model binding
for example when you have a model named Department you write your route like this:
Route::get('/{department}', [DepartmentController::class, 'showDepartment']);
and in the controller:
public function showDepartment(Department $department) {
return 'Hello from depratment';
}
When your department exists it returns the response otherwise return 404.
You may need a Department model class. Then you can find the item from database by id $department = Department::findOrFail($id);
you are send parameter in route and this function without any parameter
route :
Route::prefix('departments')->group(function() {
Route::get('/{id}', [DepartmentController::class, 'showDepartment']);
});
your function in controller should be
public function showDepartment($id) {
$department = Department::findOrFail($id);
}
}

How get data having relationships between tables using Laravel

I have an API with Laravel, and I have decided to use relations between tables, I have related them using these functions in all migrations:
// Migration file: 2020_05_26_185555_create_customers_table.php on line 27
$table->foreign('user_id')->references('id')->on('users');
And then I've implemented functions like the following:
(which get the records it's related to):
// Model app\User.php on line 80
public function customers()
{
return $this->hasMany(Customer::class);
}
On Customers controller, How can I use the function to show above to list all the clients of that user** , that is, replace the following code:
// Controller Customer\CustomerController.php on line 17
public function index()
{
$user_id = Auth::id();
$customers = Customer::where('user_id', $user_id)->get();
return $this->showAll($customers, 200, $filters);
}
For something like the following (Just an example, it doesn't work, but it's the idea of ​​what I mean):
// Controller Customer\CustomerController.php on line 17
public function index()
{
$customers = User::customers(); // Ejemplo
return $this->showAll($customers, 200, $filters);
}
My goal is to create relationship between relevant table, example, a user's clients** , without using a condition, like my current implementation of code.
Can someone help me with this?
You can use the dynamic property for the relationship to access it (and have it loaded):
public function index()
{
$user = Auth::user();
$customers = $user->customers;
...
}
Laravel 7.x Docs - Eloquent - Relationships - Relationship Methods vs Dynamic Properties

Pass variable to laravel method from within the same model

I am working on some multi tenancy updates to a Laravel app but hitting an issue when trying to pass a specific team ID into a method on a model from within another method.
Example:
In Controller:
$waitTime = $booking->estimatedWaitTime($teamId);
In Booking model:
public function queueLength()
{
$booking = $this->todaysBookings;
foreach ($bookings as $booking) {
// Calculate the length of all bookings
}
}
public function todaysBookings()
{
return $this->hasMany('App\UserBooking')->whereHas('booking', function ($q) {
$q->where('team_id', 2);
});
}
This correctly returns the bookings and allows me to loop through them in the queueLength method. However, I want to be able to pass the team_id into the todaysBooking method.
When instead calling todaysBookings as a method:
$booking = $this->todaysBookings();
It doesn't return anything for me to loop through.
Any ideas how to achieve what I want to do here?
You can pass the id as parameter and then get the results :
public function todaysBookings($team_id)
{
return $this->hasMany('App\UserBooking')->whereHas('booking', function ($q) use($team_id) {
$q->where('team_id', $team_id);
});
}
In the call you can do as follow :
$some_teame_id = 2;
$booking = $this->todaysBookings($some_teame_id)->get();
Why ?
Because the relationships in laravel serve as powerful query builders (documentation) :
Eloquent relationships are defined as methods on your Eloquent model
classes. Since, like Eloquent models themselves, relationships also
serve as powerful query builders, defining relationships as methods
provides powerful method chaining and querying capabilities.
Relationship Methods Vs. Dynamic Properties :
The call of the relationship as Methods is needed when you want to add some more conditions and filters like this :
$booking->todaysBookings()->where('active', 1)->get(); //just an example :)
And if you do not need to add additional constraints to an Eloquent relationship query, you may simply access the relationship as if it were a property, Laravel will add the get() for you :)
$booking->todaysBookings

Laravel query writing

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

Relational databases and CodeIgniter

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

Categories