Get all records in cakephp3 using TableRegistry? - php

My Demo Controller (DemoController.php):
<?php
namespace App\Controller;
class DemoController extends AppController
{
public function users()
{
$this->loadmodel('registration');
$result = $this->registration->getAllUsers();
$this->set('user_data',$result)
}
}
?>
My registration model (registration.php):
<?php
namespace App\Model;
use Cake\ORM\TableRegistry;
class Registration extends AppModel {
$articles = TableRegistry::get('registration');
public function getAllUsers()
{
return $query = $articles->find();
}
}
?>
My View:
path -- src/Template/Demo/users.ctp
but it's getting error like this (in below image) --

Your model should be named RegistrationsTable, and be in src/Model/Table/RegistrationsTable.php. Load it with loadModel('Registrations'). (It's your entity that should be named Registration.) To use your custom finder method, name the function findAllUsers, fix the signature per the documentation (should take two parameters: Query $query, array $options) and call it as $this->Registration->find('all_users');.
And why are you trying to initialize a $articles variable as the registrations model inside the registrations model (but outside of any function)? So much mess...

Related

Laravel Eloquent Relationship with different foreign key

Laravel version is 7.0:
I have setup model relationships like this.
<?php
namespace App;
class Template extends Model
{
protected $fillable = ['header_id', 'content', 'name'];
public function header()
{
return $this->belongsTo('App\Header', 'header_id');
}
}
In controller I can get template object with header.
<?php
namespace App\Http\Controllers;
use App\Template;
class TemplateController extends Controller
{
public function show($id)
{
$template = Template::find($id);
}
}
Now I can use $template->header in view.
How can I pass different header_id and get header relationship object?
I would like to do as following:
<?php
namespace App\Http\Controllers;
use App\Template;
class TemplateController extends Controller
{
public function show($id, $temp_header_id)
{
$template = Template::find($id);
$template->header_id = $temp_header_id;
}
}
I want to get new header relationship in view:
Is there any way to return new header relationship when I do $template->header in view.
Thank you
Yes you can do what you are looking to do, but kinda defeats the relationship in the database. You can assign any id to $template->header_id and then load the relationship using that new value:
$template->header_id = 897;
// load the relationship, will use the new value
// just in case the relationship was already loaded we make sure
// to load it again, since we have a different value for the key
$template->load('header');
$template->header; // should be header with id = 897

Slim 3 & Eloquent call more than 1 tables in single Model file

Recently I've been learning to use Slim 3 and eloquent.
What I'm trying to do is this (if it's even possible that is)
So I have a Model.php file
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as Model;
use Illuminate\Database\Capsule\Manager as DB;
class Course extends Model{
protected $table = "courses";
public function GetCourses(){
}
}
?>
And my Controller.php
<?php
namespace App\Controllers;
use App\Models\Course;
use Slim\Views\Twig as View;
class CourseController extends Controller{
public function index($request,$response){
return $this->view->render($response,'course/CourseNew.twig',$data);
}
}
?>
So my question is inside the Model.php is it possible to call another table somehow?
I've already called mine with protected $table = "courses"; I kind of understand that the table i defined is for the whole Class but is there a way or a workaround?
The main idea here is that i have some database tables that are very small and are not worth making another Model files for them
If this is not possible what is the alternative?
Do I have to make another Model file and call it on top of my controller where i need it use namespace App\Models\"new_model";
I would recommend to separate the data structure from the data access logic. For example: put the code for the database queries into a Repository. A repository does not care where the data comes from (table x or table y).
Example
<?php
namespace App\Repository;
use App\Model\Course;
class CourseRepository extends Repository
{
public function __construct(Connection $db)
{
$this->db = $db;
}
public function findCourceById(int $courseId): ?Course
{
// execute query here
//$this->db->....
return $course;
}
public function findSomething(): array
{
// execute query here
//$this->db->....
return $rows ?: [];
}
}

Laravel clean code

I am writing system for players where I use Laravel freamwork (just for learn) and I have question for more experience developer. I have one function which return me some data to view. I use this function in 3 controllers (but i copy and paste this function to each Controller files) and can I just put this function in one file and then use it in these 3 controllers? How can I use the same function in diffrent controller without copy and past?
You can also use Traits to share methods, however, traits are more usually for describing characteristics and types.
You should create a utility class, or use consider an abstract controller class if this is desired.
You can create Base Controller:
<?php
namespace App\Http\Controllers;
class BaseController
{
protected $playersRepository;
public function __construct(PlayersRepository $playersRepository)
{
$this->playersRepository = $playersRepository;
}
}
Which is injected with a repository object:
<?php
namespace App\Http\Controllers;
class PlayersRepository
{
public function getPlayers()
{
return Player::all();
}
}
Which has a common method, that can be used in more than one extended controller:
Games
<?php
namespace App\Http\Controllers;
class Games extends BaseController
{
public function index()
{
return view('games', ['players' => $this->playersRepository->getPlayers()]);
}
}
Matches
<?php
namespace App\Http\Controllers;
class Matches extends BaseController
{
public function show()
{
return view('matches', [
'matches' => $matches,
'players' => $this->playersRepository->getPlayers()
]);
}
}
Create module (util) or override main Controller class.

Accessing model methods from controller class Laravel

I am new to Laravel, I am trying things around while going through a tutorial. This is where I am facing an unexpected behaviour.
I have a model tweet and a controller named tweetsController; when I call tweet::find() or any similar method I found this:
FatalErrorException in tweetsController.php line 13:
Class 'App\Http\Controllers\tweet' not found
I have also tried App\tweet::find().
Everything seems fine through tinker.
Please explain.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class tweetsController extends Controller
{
public function show(){
$data = tweet::first()->tweetBody;
return view('tweets.list',['passedData'=> $data]);
}
public function delete($id){
return "here we dele the tweet ".$id;
}
public function add(){
return "i add your tweet to database then show you all the tweets";
}
}
tweet.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class tweet extends Model
{
protected $fillable = array(
'tweetHead',
'tweetBody'
);
}
?>
A few options the maybe generating this error:
The model/controller namespace is incorrect;
The name of the file and the class name for the model needs to be "Tweet" with the first letter in uppercase;
If you set the right namespace on the model "Tweet.php" and import that on your "TweetController.php"
I hope that helps :)
UPDATE:
In the TweetController.php add this
use App\Tweet;
Before the class declaration, like this
use App\Tweet;
class tweetsController extends Controller
{
And remember to change the controller name in the class declaration like this
class TweetsController extends Controller
{
And the controller filename will become "TweetsController.php"
The Model also has to be named "Tweet" and not "tweet" in the class declaration and the filename
class tweet extends Model
will become
class Tweet extends Model
and the file will be named "Tweet.php"
and everytime you need to call the model you will do this
public function show(){
$data = App\Tweet::first()->tweetBody;
return view('tweets.list',['passedData'=> $data]);
}
Add use Add\User below namespace in your controller

How to call a model function inside the controller in Laravel 5

I have been facing a problem of not able to use the model inside the controller in the new laravel framework version 5. i created the model using the artisan command
"php artisan make:model Authentication" and it created the model successfully inside the app folder, after that i have created a small function test in it, and my model code looks like this.
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function test(){
echo "This is a test function";
}
}
Now i have no idea, that how shall i call the function test() of model to my controller , Any help would be appreciated, Thanks in advance.
A quick and dirty way to run that function and see the output would be to edit app\Http\routes.php and add:
use App\Authentication;
Route::get('authentication/test', function(){
$auth = new Authentication();
return $auth->test();
});
Then visit your site and go to this path: /authentication/test
The first argument to Route::get() sets the path and the second argument says what to do when that path is called.
If you wanted to take this further, I would recommend creating a controller and replacing that anonymous function with a reference to a method on the controller. In this case, you would change app\Http\Routes.php by instead adding:
Route::get('authentication/test', 'AuthenticationController#test');
And then use artisan to make a controller called AuthenticationController or create app\Http\Controllers\AuthenticationController.php and edit it like so:
<?php namespace App\Http\Controllers;
use App\Authentication;
class AuthenticationController extends Controller {
public function test()
{
$auth = new Authentication();
return $auth->test();
}
}
Again, you can see the results by going to /authentication/test on your Laravel site.
Use scope before method name
<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
class Mainmenu extends Model
{
public function scopeLeftmenu() {
return DB::table('mainmenus')->where(['menu_type'=>'leftmenu', menu_publish'=>1])->orderBy('menu_sort', 'ASC')->get();
}
}
above code i tried to access certain purpose to call databse of left menu
than we can easy call it in Controller
<?php
Mainmenu::Leftmenu();
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function scopeTest(){
echo "This is a test function";
}
}
Just prefix test() with scope. This will become scopeTest().
Now you can call it from anywhere like Authentication::Test().
For me the fix was to set the function as static:
public static function test() {..}
And then call it in the controller directly:
Authentication::test()
You can call your model function in controller like
$value = Authentication::test();
var_dump($value);
simply you can make it static
public static function test(){
....
}
then you can call it like that
Authentication::test();
1) First, make sure your Model is inside a Models Folder
2) Then supposing you have a model called Property inside which you have a method called returnCountries.
public function returnCountries(){
$countries = Property::returnCountries();
}
of course, in your case, replace Property by the name of your Model, and returnCountries by the name if your function, which is Test
and in the Model you write that function requesting the countries
so in your Model, place a:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function test(){
return $test = "This is a test function";
}
}
and this is what your Controller will be getting
You should create an object of the model in your controller function then you can model functions inside your controller as:
In Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function test(){
return "This is a test function"; // you should return response of model function not echo on function calling.
}
}
In Controller:
namespace App\Http\Controllers;
class TestController extends Controller
{
// this variable is used to store authenticationModel object
protected $authenticationModel;
public function __construct(Request $request)
{
parent::__construct($request);
$this->authenticationModel= new \App\Authentication();
}
public function demo(){
echo $this->authenticationModel->test();
}
}
Output:
This is a test function

Categories