I´ve been trying to make an accessor work a few hours now, to no avail. I have simplified my model code to the bare bones, and still no luck.
Here´s the code in PersonaIdentificacion.php:`
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PersonaIdentificacion extends Modelo
{
public $table = "personaidentificacion";
public function getFooAttribute() {
return 1;
}
}`
I use Artisan Tinker to try and retrieve the value of the 'foo' property, but I only get: 'null'. I don´t get it. What am I missing??
Your getFooAttribute() is fine.
To your model add the following assuming that it's a new attribute
protected $appends=['foo'];
and then you can call
$id = App\PersonaIdentificacion::first(); $id->foo;
This should work fine.
Related
Im new to laravel, i am trying to query a specific table in my DB. I only have 1 data table and the standard user auth tables. I am getting a error: BadMethodCallException
Call to undefined method App\Figures::table().
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Figures extends Model
{
}
controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Figures;
class figuresController extends Controller
public function figurespag2() {
$dummyDetails = Figures::table('figures')->where('name', 'batman');
return view ( 'pagination2.index' )->withUsers($dummyDetails);
}
route
Route::get ( '/pagination2', 'figuresController#figurespag2' );
I know it's going to be something obvious, but I am new to this.
this is wrong
$dummyDetails = Figures::table('figures')->where('name', 'batman');
Method 1---------- laravel eloquent
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Figures extends Model
{
protected $table = 'figures';
}
Controller
$dummyDetails = Figures::where('name', 'batman')->get();
and
Method 2 ---------- laravel Query Builder
$dummyDetails = \DB::table('figures')->where('name', 'batman')->get();
Use this you not need to define table name
public function figurespag2() {
$dummyDetails = Figures::where('name', 'batman')->get();
return view ( 'pagination2.index' )->withUsers($dummyDetails);
}
First you may need to know laravel model rules.
If you create a table name like "figures" (plural) you need to create its model by Figure (singular).
if you create a table other then this rule then you have to mentioned table name in model like this.
protected $table = "table_name";
you can access table with where condition in controller like this.
public function figurespag2() {
$dummyDetails = Figure::where('name', 'batman')->get();
return view ( 'pagination2.index' )->withUsers($dummyDetails);
}
Hope this may help you.
I'm trying to map an existing one to one relationship in my database using Eloquent following the Laravel tutorial and I'm receiving a string conversion error.
I have to use an existing database that is used by other program, so I can't change the database structure.
This are my models:
Pessoa.php
namespace App\Models;
use Illuminate\Support\Facades\Log; use
Illuminate\Database\Eloquent\Model;
class Pessoa extends Model {
protected $table = 'pessoas';
public function estadoCivil(){
//return EstadoCivil::find($this->estado_civil_id);
return $this->hasOne('App\Models\EstadoCivil', 'estado_civil_id');
}
}
EstadoCivil.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class EstadoCivil extends Model
{
protected $table = 'estados_civis';
}
I don't know what to do, but I am getting this error:
Object of class Illuminate\Database\Eloquent\Relations\HasOne could not be converted to string
I searched for typos and other mistakes and couldn't find anything. I'm not even trying to convert anything to string to get this error, the types in the database for the id and the foreign key are the same too.
Here is the controller that is using it:
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Pessoa as Pessoa;
class Eu extends Controller
{
public function __construct()
{
}
public function dadosCompletos(Request $request){
return Pessoa::find($request->user()->pessoa_id)->estadoCivil();
}
}
If I just use return Pessoa::find($request->user()->pessoa_id) it works fine and returns the data correctly from pessoas table.
you are returning the relation not the actual EstadoCivil collection.
use return Pessoa::find($request->user()->pessoa_id)->estadoCivil without parenthesis
You have to use ->estadoCivil instead of ->estadoCivil()
I get this error that says, "No query results for the model [App\dummy]." I believe the problem is in the controller. When you submit the form it is supposed to trigger the function in the comment controller. This controller is new so, I believe the error is in here. That is when it stopped working. Here is the commentController file:
<?php
namespace App\Http\Controllers;
use App\Dummy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; //this one is for sql builders
use App\Comments;
use Illuminate\Http\RedirectResponse;
use DateTime; //to create a new date object you need to include this namespace
class commentController extends Controller
{
public function store(Dummy $post){
$date = new DateTime();
$timestamp = $date->getTimestamp();
$id = $post->id;
$post->addComment(request('body'));
return view('post', compact('post', 'timestamp', 'id'));
}
}
I tried making App\Dummy lowercase so it was App\dummy but still it didn't work. It still gives me the error.
Here is my dummy model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class dummy extends Model
{
protected $guarded = [];
public function comments(){
return $this->hasMany(Comments::class, 'post_id');
}
public function addComment($body){
$this->comments()->create(compact('body'));
}
}
Your error is that your class is called dummy buy you are using it as Dummy, so rename it both (file and class) to Dummy.
This class dummy extends Model to this class Dummy extends Model.
Remember that your file should be called Dummy.php too, not dummy.php
Change your model class name to Dummy and file name to Dummy.php.
Your main problem here is the route model binding. When you're trying to add a comment, the $post object is not getting resolved based on your route. You have bad a route setup or trying to add comment to a non existent post.
Basically the error message No query results for the model happens because of this code that the route model binding does for you.
$post = Dummy::findOrFail($id);
Try changing this
Route::post('post/{dummy}/comments', 'commentController#store');
public function store(Dummy $dummy)
The problem was in the form. The action attribute in the form was something like this:
<form class="col s12" action={{ url('/post/$id/comments') }} method="post">
I thought that would get the id because I compacted the id into the variable $id. But then I checked the url and noticed not a number but the actual word $id. So, here is the solution:
<form class="col s12" action={{ url('/post/' . $post->id . '/comments') }} method="post">
Just to let you guys know that when it said, "No query results for the model [App\dummy]." It meant that when I used this method from the dummy model which had this line of code:
public function comments(){
return $this->hasMany(Comments::class, 'post_id');
}
It couldn't find the primary key from the dummies table. Therefore couldn't connect with the foreign key which is the post_id from the comments table. So, it wasn't able to submit the new comment to the table for that unique blog post. This is the last part that submits the comment to the table:
public function addComment($body, $name){
$this->comments()->create(compact('body', 'name'));
}
by the way comments() is the method I created that i just showed before.
Conclusion
It pretty much stopped working in the web.php file(routing file) because it wasn't getting an id. Due to the mistake I made in the action attribute in the form that i explained before.
My repository is like this :
<?php
namespace App\Repositories;
use App\Models\UsersBank;
use Illuminate\Contracts\Container\Container;
use Rinvex\Repository\Repositories\EloquentRepository;
class UserBankRepository extends EloquentRepository
{
public function __construct(Container $container)
{
$this->setContainer($container)
->setModel(UsersBank::class)
->setRepositoryId('rinvex.repository.uniqueid');
}
}
My model is like this :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UsersBank extends Model
{
protected $fillable = ['user_id','bank_id','status','account_name','account_number'];
}
My service is like this :
public function setMain($id)
{
$param['status'] = 1;
$this->user_bank_repository->update($id, $param);
}
When setMain function executed, It will update field status = 1 by the id
I want to update status = 1 to all record. So, Not by id
How can I do it?
Note :
Update which I mean here is the update via the repository. Not update through a model
Look into the source code of update() method of the package and you'll see it's impossible, so you'll need to use foreach() and create a bunch of queries.
My opinion is this and similar packages are useless since they are still using Eloquent and do not provide any handful functionality. I'd recommend you to use Eloquent directly to update all rows with just one query:
Model::query()->update(['status' => 1]);
My ultimate goal is to print the contents of a table in a database to a table in HTML using Laravel's ORM.
Beyond that I know how to configure the database file, but is there any other things i need to configure.
From my understanding I need three files. Do i need to make a controller? If so how does that work?
Item Class
Route.php
views.php
Here is what I have so far
Item.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model {
protected $table = 'items';
protected $primaryKey = 'item_id';
public function products()
{
return $this->belongsTo('item_id', 'item_name', 'item_cost');
}
}
routes.php
<?php
Route::get('Product', function()
{
$products = \App\items::all();
return view('Items', $items);
});
and I have no idea how to create a view in HTML.
I know I'm completely off at this point, but I've read the documentation and I am still completely lost when they reference things like URI and have URL in the same sentence without defining or even linking to it elsewhere in the documentation.
Actually, you have declared your Eloquent ORM like this:
class Item extends Model {
// ...
}
But you are using that model/class like this:
$products = \App\items::all();
In this case, \App\items doesn't exist, it should be:
$items = \App\Item::all(); // <-- Item not items
return view('items', $items); // <-- $items not $products
You asked: Do i need to make a controller?
In this case, no, it'll work fine with the anonymous function but using a Controller is better for many reasons.
Update:
Create a view in resources/views as items.blade.php and you can print out the items through a foreach loop. Check the documentation.