Ordering table data - laravel

I already read this piece from the laravel 5.1 documentation:
$users = DB::table('users')
->orderBy('name', 'desc')
->get();
I have no ideia where to write that.
And this is what I tried to write inside my Model:
class Professor extends Model
{
$professor = DB:table('professor')->orderBy('name','asc')->get();
}
Also tried:
class Professor extends Model
{
Professor::orderBy('name')->get();
//$professor = Professor::orderBy('name')->get();
}
Nothing works e.e
All of them give me erros like:
syntax error, unexpected '$professor' (T_VARIABLE), expecting function (T_FUNCTION)

The piece of code your trying to write should not be placed inside a Model. It should be in a controller or a repository if your using a Repository Pattern.
Assuming you got the following in your code.
A table called professors. A model Professor . A Controller called ProfessorsController.
And a route file with the following code get('professors','ProfessorsController#index');
Then on the controller you should have the following code.
class ProfessorsController extends Controller {
public function index()
{
$professors = \DB:table('professors')->orderBy('name','asc')->get();
return view('proffesors')->with('proffessors',$professors);
}
}
This will return an order list of professors to the view. That is if you are using a view to represent the data.

It does not need to be in model. Most of time something like that goes in controller.
In model you need to define relations or functions that would be used application wide on a object.
If you want to do something similar in model you won't use DB::table you need something like:
class Professor extends \Eloquent
{
public function professorsByName(){
$professionCollection = Professor::all()->orderBy('name','asc')->get();
return $professionCollection;
}
}
Please take it as example it's not something that should go in model at least this simple not.
Mental Note
Never use DB::table reason your observer if any won't execute.

I think you all are missing the primary issue with
class Professor extends Model
{
$professor = DB:table('professor')->orderBy('name','asc')->get();
}
This is not how PHP classes work.
OP, you need to brush up on the concepts of OOP.
What you need is something like this:
your controller:
public function myRoutedMethod()
{
$professors = Professor::getModel()->orderBy('name','asc')->get();
foreach($professors as $professor)
{
var_dump($professor->toArray();
}
}
Or probably even better, create a repository to interface with your model and just call $repository->professors()->toArray();
Google search: Laravel Repository

Related

How to add my course Slug before lecture in url path?

i'm currently doing a project for my homework, which i didn't managed to see something like this to fix my problem.
I have 2 models with Course and CourseLecture name. and i'm using getPathAttribute in my class base on a tutorial in internet.
in my Course Model i'm using getPathAttribute like this :
public function getPathAttribute()
{
return "/clientside/instructor/courses/$this->slug";
}
and in my CourseLecture Model :
public function getPathAttribute()
{
return "/clientside/instructor/courses/{course}/lectures/$this->slug";
}
I need to put my course slug to this getPathAttribute like :
http://url.com/clientside/instructor/courses/php/lectures/one
also my CourseLecture is using course_id and i've got a relationship between them which, they're belongsTo' andHasMany'. so how can i add course slug base on this structor in this path?
Also for this homework, i'm using Vue.js/Laravel. and it's a spa. i've tagged vue.js bcs if there's any solution to fix this via router, I will be happy to use it.
You can dynamically grab course slug from the course() relationship defined on the CourseLecture model. See below:
In CourseLecture model:
protected $appends = ['path'];
// relationship
public function course()
{
return $this->belongsTo(Course::class);
}
public function getPathAttribute()
{
return "/clientside/instructor/courses/{$this->course->slug}/lectures/$this->slug";
}

Where can I store my big SQL queries in Laravel?

I have a problem in my Laravel structure because I need to add many reports to my app, so I think it's not a good idea to put everything in the controller because my eloquent models allow me to list, add, insert and update, and my queries need more than one table with joins, and some math functions like sum(), max(), min().
When I used Codeigniter, I added methods with each query in the model file.
So I can call it $sales->salesReport() and it gave me the data.
The question is really a matter of what is being done and what is responsible. There are some excellent posts on where logic should be kept and what can be used. I am a little unclear as to whether you are asking about chaining something like scopes or more just where to put your logic. I would probably have a service:
<?php
class SalesReportService {
public function generateReport(Sales $sales)
{
// logic here...
return $result;
}
}
and then in the controller it would be something like:
<?php
class SalesController extends Controller {
public function __construct(SalesReportService $reportService)
{
$this->reportService = $reportService;
}
public function show(Sales $sales)
{
return $this->reportService->generateReport($sales);
}
}
Laravel offers something similar to Codeigniter that matches what you described. It's called query scopes, or more precisely local scopes. You can keep them in your model and call them whenever you want.
You add in your model
public function scopeSalesReport($query) {
return $query->join(...);
}
Source: https://laravel.com/docs/5.4/eloquent#local-scopes

Laravel 5 fetching related data using 3 models

hello guys I have this set of database
clients(#id,raison_sociale,adresse,)<br>
delivery(#id,client_id(fk),date_del) <br>
details(delivery_id(fk),product_id(fk),qt)
product(id,code,desig,price)
and here are my eloquent relationships
class Client extends Model {
public function livraison (){
return $this->hasMany('App\Models\Livraison'); } }
class Detail extends Model
{
public function delivery (){
return $this->belongsTo('App\Models\Delivery');}}
class Livraison extends Model{
public function client (){
return $this->belongsTo('App\Models\Client');
}
public function detail (){
return $this->hasMany('App\Models\detail'); }}
Do I have something wrong with these relationships ?
I have a page where I show all of my delivery but I can't find the correct way to fetch this row:
raison_soc(from client) & date_del(from delivery); and details table (for each client of course )
use App\Models\Client;
Client::with('delivery.detail')->get();
I can't test your relationships but assuming you are following the naming conventions your relations should be fine. The above will grab all details that are associated to the delivery by the client.
You could improve your relationship with a hasManyThrough method Has Many Through
You would do something like this in your Client class:
public function details(){
return $this->hasManyThrough('App\Models`Details', 'App\Models\Livarasion');
}
If you explain your 2nd point more clearly I can help you adjust this. Please let me know if you have any issues

Laravel 4 Use the same Model and Controller for 12 lists for selects

I have to meke models, controllers and views for 12 tables. They have all the same structure id, name, order.
I was thinking and maybe using:
Controller
index($model)
$model::all()
return View::make(all_tables,compact('model'))
edit($model,$id)... and so on.
But and don't know if there's a way for using only one model.
Did anybody do anything like this?
Any idea?
Thanks
Although each model has the same table structure, what you're trying to achieve would not be advisable as you'd lose a lot of the fluent capabilities of Laravel's Eloquent ORM.
Regarding the controller, this would work:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class GenericModelController extends Controller
{
public function loadModelById($model, $id)
{
$instance = \App::make('App\\' . ucfirst($model));
return $instance->find($id);
}
}
You'll need the following route:
Route::get('show/{model}/{id}', 'GenericModelController#loadModelById');
Example, to load a user with an id of 1:
http://www.yourdomain.com/show/user/1
Edit: I just saw that you're using Laravel 4, so the syntax for defining a route will be a little different I believe but the general concept will still work. Testing in Laravel 5 and works perfectly.
You should get get some idea from here.Please use the link below.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel
// app/models/Bear.php
class Bear extends Eloquent {
// MASS ASSIGNMENT -------------------------------------------------------
// define which attributes are mass assignable (for security)
// we only want these 3 attributes able to be filled
protected $fillable = array('name', 'type', 'danger_level');
// DEFINE RELATIONSHIPS --------------------------------------------------
// each bear HAS one fish to eat
public function fish() {
return $this->hasOne('Fish'); // this matches the Eloquent model
}
// each bear climbs many trees
public function trees() {
return $this->hasMany('Tree');
}
// each bear BELONGS to many picnic
// define our pivot table also
public function picnics() {
return $this->belongsToMany('Picnic', 'bears_picnics', 'bear_id', 'picnic_id');
}
}
I find a simple way.
Only one model, one controller and one view(index,edit, etc) too.
A single table with
id, name of list, value (name to appears in the list)
Yo pass can pass to de view all the values per list, and for any list in the table you can create de select if it's no empty.

Laravel eager loading result

I'm having trouble with eager loading in laravel
I have these models:
class Page extends Eloquent {
public function translations() {
return $this->has_many('Pagestl', 'page_id');
}
}
and
class Pagestl extends Eloquent {
public static $table = 'pages_tl';
public function page() {
return $this->belongs_to('Page', 'id');
}
}
I want a specific page with its translation data of a specific language.
I retrieve the data like this:
$page_data = Page::with(array('translations' => function($query) {
$query->where('lang_id', '=', 'nl')->first();
}))->find($id);
De result is ok-ish. I get all the page data and the translation of 1 language, dutch (nl). But in order to get a field from the language data I have to this:
$page_data->translations[0]->attributes['content_or_whatever'];
..which i find ugly. I feel i should only have to do something like:
$page_data->translations->content;
..but that gives me an error (Trying to get property of non-object).
Am I missing something or is this just the way it is?
I don't find it necessary to do eager-loading here.
Both ways of doing it will result in 2 queries: select the Page with the given id and then find its first translation.
So, I would do:
$page = Page::find($id);
and then
$page_data = Pagestl::where_page_id_and_lang_id($page->id, 'nl')->first();
Then, assuming the content field exists in pages_tl table, we'll get it by doing:
echo $page_data->content;
Finally, your code looks alright; you don't have to have the second parameter when defining the relationships unless they are different from what Laravel expects.
I'll let you find where the problem is with your code (I couldn't figure out from the information given - could be something to do with strings.php)

Resources