How can i get result from model in laravel 5 - laravel

Good day, i'm trying to get the result from my model that called with Mainmodel through my controller, my controller is MainController.
Here is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Mainmodel;
class MainController extends Controller
{
function index(){
echo "Kok, direct akses sih?";
}
function get_menu(){
$menu = app\Mainmodel::request_menu();
dd($menu);
}
}
Here is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mainmodel extends Model
{
function request_menu(){
$menu = DB::table('menu')
->orderBy('[order]', 'desc')
->get();
return $menu;
}
}
my routes
Route::get('menu','MainController#get_menu');
with my script above i get this
FatalErrorException in MainController.php line 17: Class
'App\Http\Controllers\app\Mainmodel' not found
how can i fix this ? thanks in advance.
Note: I'm bit confuse with laravel. I'm using codeigniter before. And i have a simple question. In laravel for request to database should i use model ? or can i just use my controller for my request to database.
sorry for my bad english.

I would imagine it's because your using app rather than App for the namespace.
Try changing:
app\Mainmodel
To:
App\Mainmodel
Alternatively, you can add a use statement to the top of the class and then just reference the class i.e.:
use App\Mainmodel;
Then you can just do something like:
Mainmodel::request_menu();
The way you're currently using you models is not the way Eloquent should be used. As I mentioned in my comment you should create a model for each table in your database (or at least for the majority of use cases).
To do this run:
php artisan make:model Menu
Then in the newly created Menu model add:
protected $table = 'menu';
This is because Laravel's default naming convention is singular for the class name and plural for the table name. Since your table name is menu and not menus you just need to tell Laravel to use a different table name.
Then your controller would look something like:
<?php
namespace App\Http\Controllers;
use App\Menu;
class MainController extends Controller
{
public function index()
{
echo "Kok, direct akses sih?";
}
public function get_menu()
{
$menu = Menu::orderBy('order', 'desc')->get();
dd($menu);
}
}
Hope this helps!

You can solve it by different solution. The solution is you don't have to call request_menu(); you can get it in your controller.
MainController
use use Illuminate\Support\Facades\DB;
public function get_menu(){
$menu = DB::table('menu')
->orderBy('Your_Field_Name', 'DESC')
->get();
dd($menu);
}

Related

Laravel Models/function, how to make a main "function"

So guy's, I've created a Laravel project.
I have a master. Layout which always contains the user data.
So I have a navbar with $user->name for example.
In every controller I needed to add the User model and also the where function.
$user = User::find(auth()->user()->id)
Maybe this example is bad, but I've also included the company in the master, so it shows in the Navbar.
Is there a way, that I don't need to repeat that process? So I don't need it always in the controller.
Thanks for reading.
In laravel you are extending each class from a main controller so its better to create a method in main class like this
child controller
class testController extends Controller
{
// as you can see its extending so go into Controller class
}
parent class, So here i have creatd a getName method here. If you want get the value through mode
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
private $current_user_name = 'test';
public function getName()
{
return ($this->current_user_name);
}
}
Now go back to child controller and pass this method in view
class testController extends Controller
{
public function index()
{
return view('', $data = ['name' => $this->getName()]);
}
}
Hope this cover your query. In this way you don't need to repeat your code in every controller.
You can get data in your blade template too, like user information, but if you need more complex data and you don't want to put logic in blade, you can use this method (AppServiceProvider.php):
public function boot()
{
view()->composer('your_mast_layout', function($view)
{
$data = ...
$view->with('variable_name', $data);
});
}

Define a variable not explained

Sorry for the dumb question but can anyone please tell me how to define a variable in very simple terms? I have struggled for several months with "undefined variable" errors. Are variables stored in config? Or maybe in routes?
I have a database with a customers table. When I put this on my view home page {{$customers->name}} I get Undefined variable: customers.
Fine. So how and where do I define a variable. I would have thought it WAS defined given that the database table is literally called customers. Ugh!
My model file Customer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = ['name', 'phone'];
public function address()
{
return $this->hasOne(CustomerAddress::class);
}
public function purchases()
{
return $this->hasMany(CustomerPurchase::class);
}
}
Undefined variable means the variable does not exist and the reasons for your case is, you did not pass it in the view.
Usually, to get the customers records from the database to your views, you can do it in several ways:
Query it prior to loading your view then pass it to your views:
//doing it in the controller
//create a controller: php artisan make:controller CustomerController
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use App\Customer; //Dont forget to import your Customer model
class CustomerController extends BaseController
{
public function index()
{
$customers = Customer::get(); //this will fetch the customer using your mdoel
return view('customer', ['customers' => $customers]); //this will pass the records to the view
}
}
//then in your routes/web.php:
Route::get('/customers', 'CustomerController#index'); //when you go to your application/customers in the browser, it will go to the controller and return the view with the records.
//OR you can skip the controllers and do it in the routes/web.php directly as what #jitesh jose mentioned.
Query straight into your view (Not really recommended, but sometimes you just need to make it work)
In your customer.blade.php
#php
$customers = \App\Customer::get();
#endphp
<ul>
#foreach($customers as $customer)
<li>{{$customer->name}}</li>
#endforeach
</ul>
My advice, try to watch a few basic Laravel videos so that you will understand the flow of the request and response.
If your model name is Customer,laravel automatically pick the table name as customers.Otherwise you have to use your desired table name in Model as follows.
protected $table = 'customers_table';
In your web.php
Route::get('/home',function () {
$customers = DB::table('customers_table')->get();
OR
$customers = Customer::get();
return view('welcome')->with('customers',$customers);
});
You can use$customers in welcome.blade.php as
#foreach($customers as $customer)
{{$customer->name}}
#endforeach

Laravel - Notifications Controller can't use method user()

I'm trying to add notification system to my Laravel project. I' watched this video to understand the system : https://www.youtube.com/watch?v=iDDUxqpNgSc
Notification table, model et controller are created. Also, i have created the view with Vue.JS and Pusher. It's work well !
However, in the notification controller, when i try to user Auth::user() method it's return null. I read somewhere it's because the middleware 'auth' is not already load when the controller is.
This is my NotificationsController file :
<?php
namespace App\Http\Controllers;
use App\Notification;
use Illuminate\Http\Request;
use App\Idea;
use App\User;
use Illuminate\Support\Facades\Auth;
class NotificationsController extends Controller
{
public function __construct()
{
}
function get(){
$notification = Auth::user()->unreadNotifications()->get();
return $notification;
}
function read(Request $request){
Auth::user()->unreadNotifications()->find($request->id)->markAsRead();
}
}
Do you have any idea how to solve this ?
Thank's for your time !
The answer was not about the Auth::user (It's accessible). I just baldy defined the notifiable_type in my model. It was App\Idea, it should be App\User

Routing in Laravel is not working

I am using laravel 5.0
I am trying to route the following. But it is not working
Route::post('accesscontrols/permissions', 'AccescontrolsController#permission');
I don't know what error in this.
It does not access permissions function in AccesscontrolsController
I have a function in AccesscontrolsController
public function permission()
{
$roles = DB::table('roles')->get();
$permissions = DB::table('permissions')->get();
return view('accesscontrols.permission', compact('roles', 'permissions'));
}
What I have did wrong?
Your route declaration should be made in app/Http/routes.php.
Also, make sure that your controller is within the App\Http\Controllers namespace and that it extends App\Http\Controllers\Controller.
Ex:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function permission()
{
...
Also, if you whish to test it in the browser (by typing "accesscontrols/permissions" in the address bar), you route should answer to the GET verb. Try to declare it using Route::get( instead.
You are returning a view in your method and you are not working with any POST data, which is strange. Are you sure you want POST request and not GET?

Polymorphic relations in upgraded Laravel app from 4.2 to 5

Short: some related models are returning instances correctly, but some aren't (the polymorphic ones).
I have those three models:
app/Models/User.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function company()
{
return $this->hasOne('App\Company');
}
}
app/Models/Company.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model {
public function user()
{
return $this->belongsTo('App\User');
}
public function address()
{
// Also tested with morphMany, without success
return $this->morphOne('App\Address', 'addressable');
}
}
app/Models/Address.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model {
public function addressable()
{
return $this->morphTo();
}
}
And the controller:
app/Http/Controllers/MyController.php
<?php namespace App\Http\Controllers;
// ... many "use" clauses not relevant to the question
use Auth;
// ...
use App\Address;
use App\Company;
use App\User;
class MyController extends Controller {
// Ok here
$user = Auth::user();
// Ok here, too
$company = $user->company()->first();
// Here is the problem; $address is null
$address = $company->address()->first();
}
The line $company->address()->first(); is always returning null to $address in Laravel 5, but it worked well in Laravel 4.2
In L4 models were not namespaced by default, so they were saved as ModelName in your table, while now in L5 they are rather Namespace\ModelName and are retrieved the same way.
That said, your data saved in L4 needs to be adjusted so it matches your current models, or you can use protected $morphClass on the models.
However take this into consideration for the latter solution.
If you open your database - you'll see the relationship in your old L4 data stored as: User or Company
You need to run a script that updates the columns to the new namespace names - such as App\User or App\Company
This is because you are now namespacing your models - so Laravel needs to know which namespace to call.
Along with #The Shift Exchange's answer and following my question's example, you can follow this approach:
Instead of adding the namespace in addressable_type column values from address table (and this is a valid solution), you can use $morphClass:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model {
protected $morphClass = 'Company';
public function user()
{
return $this->belongsTo('App\User');
}
public function address()
{
// Also tested with morphMany, without success
return $this->morphOne('App\Address', 'addressable');
}

Resources