I used laravel Auditor in a model and it works very well as following:
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable;
class Contracts extends Model implements Auditable
{
use \OwenIt\Auditing\Auditable;
protected $fillable=['condatereceived'];
public function user()
{
return $this->belongsTo(User::class);
}
}
But I want to used it in the controller as :
public function updatecomplated(Request $request, $id,Contracts $contract ,Auditor $auditor)
{
Contracts::where('id', $id)
->update(['complated' => 50, 'conuploadby' => Auth::id(),'constatus' =>'Need To Active' ]);
if ($audit = $auditor->execute($contract)) {
$auditor->prune($contract);
}
return redirect()->back();
}
The code in controller give me error:
Call to undefined method OwenIt\Auditing\Facades\Auditor::execute()
any ideas to use auditor in the controller, please.
try this package its easy with good documentation
simply add this to your table
$table->auditable();
and this to your model
namespace App;
use Yajra\Auditable\AuditableTrait;
class User extends Model
{
use AuditableTrait;
}
thats it now simply get your auditor by calling
$user->creator // for who create
and
$user->updater //for who update data
for more information click here for check trait
Hope this helps
Related
I’m kind of new to Laravel and the whole API architecture, so my question may seem dumb at first.
My basic setup:
Laravel 8;
PHP 8;
routes\api.php
Route::post('/categories/',[ApiCategoriesInsertController::class, 'insertCategories'], function($insertCategoriesResults) {
return response()->json($insertCategoriesResults);
})->name('api.categories.insert');
\app\Http\Controllers\ApiCategoriesInsertController.php (created with php artisan make:controller)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// Custom models.
use App\Models\CategoriesInsert;
class ApiCategoriesInsertController extends Controller
{
private mixed $ciAPI;
public function __construct(Request $req)
{
}
public function insertCategories(Request $req): array
{
$this->ciAPI = new CategoriesInsert(['testing'=>'debug']);
return [‘status’ => ‘OK’];
}
}
\app\Models\CategoriesInsert.php (created with php artisan make:model)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CategoriesInsert extends Model
{
use HasFactory;
public function __construct(array $objParameters)
{
}
}
When I make a post to http://localhost:8000/api/categories, Laravel logs the following error:
local.ERROR: Too few arguments to function App\Models\CategoriesInsert::__construct(), 0 passed in … Too few arguments to function App\\Models\\CategoriesInsert::__construct(), 0 passed in …
Anyone knows what’s wrong or missing in my architecture?
Thanks!
Make your model's constructor compatible with parent.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CategoriesInsert extends Model
{
use HasFactory;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
}
}
Also, notice, that when you call new CategoriesInsert(['testing'=>'debug']), you do not save the data in your database. Use:
$insert = new CategoriesInsert(['testing'=>'debug']);
$insert->save();
Or:
CategoriesInsert::create(['testing'=>'debug']);
you don't need to pass data to model
change your code to bellow code:
public function insertCategories(Request $req): array
{
CategoriesInsert::create(['testing' => 'debug']);
return [‘status’ => ‘OK’];
}
key of passed array is your filed name in database, and value stored data
also you should define fillable parameter in model
protected $fillable = [
'title',
'slug',
'priority',
];
I have a model called BrandCodeModell :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class BrandCodeModell extends Model
{
use HasFactory;
public function brand()
{
return $this->belongsTo(Brand::class, 'brand_id', 'id');
}
public function modell()
{
return $this->belongsTo(Modell::class, 'modell_id', 'id');
}
public function codeModell()
{
return $this->belongsTo(CodeModell::class, 'code_id', 'id');
}
}
And this is Modell relation with Brand Model :
public function modells()
{
return $this->belongsToMany(Modell::class)->using(BrandCodeModell::class)
->withPivot('code_id');
}
When I try too add new modell to database I get this error :
BadMethodCallException
Call to undefined method App\Models\BrandCodeModell::fromRawAttributes()
Here is my controller to save modell to database :
$brand = Brand::where('id', $id)->first();
$brand->modells()->detach();
$modells = collect($request['modells']);
$modells->each(function ($item) use ($brand) {
if (is_null($item['name'])) return;
$mod = Modell::firstOrCreate([
'name' => $item['name'],
'sort' => $item['sort']
]);
$mod_code = $mod->codeModell()->firstOrCreate([
'name' => $item['code']
]);
$brand->modells()->attach($mod->id, [
'code_id' => $mod_code->id
]);
});
In this code, Modell::firstOrCreate and $mod_code = $mod->codeModell()->firstOrCreate will be create successfully but this part of code $brand->modells()->attach($mod->id, ['code_id' => $mod_code->id]); does not work.
Where is the problem ?
Tell me if you need more details
Per the documentation:
Custom many-to-many pivot models should extend the Illuminate\Database\Eloquent\Relations\Pivot class
So your pivot class should look like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\Pivot;
class BrandCodeModell extends Pivot
{
//
}
However, unless you're adding additional methods on to the pivot class, there's no need to define it; Laravel will automatically use the appropriate pivot table. Likewise there's probably no need for it to import the HasFactory trait, as entries would be automatically created by related model creation.
I don't know if I formulated the question correctly, but whatever.
So when I use the "store" method on my controller, I send two fields, "name" and "fr", both in the same request.
In my controller, I want to be able to create my Model (Room) and attach its relationship to it (RoomTranslation). When I try the following code, it tells me I didn't provide the room_id. Is there an automatic way to achieve this ?
public function store(RoomRequest $request)
{
$request = $request->validated();
$room = new Room;
$room->create($request);
$room->translations()->create($request);
return success('');
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class RoomTranslation extends Model
{
protected $fillable = ['fr', 'room_id'];
public function room() {
return $this->belongsTo('App\Room');
}
}
<?php
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use App\RoomTranslation;
class Room extends Model
{
protected $fillable = ['name'];
public function categories() {
return $this->hasMany('App\Category');
}
public function translations() {
return $this->hasOne('App\RoomTranslation');
}
}
Thank you for your help !
P.S. : If there is a cleaner way to write this part of my code, I will be happy to hear how I can improve it.
Thank you !
You can do this:
Room::create($request->only(['name']))->translations()->create($request->only(['fr']));
just look for typo or input names to be correct.
Also in Room model class translations relation if you have multiple languages for every Room should be hasMany, And if you don't have many translations per Room you could just add a column for translation language.
I'm following the Laravel From Scratch tutorial series, I'm currently at the part that you are creating a comment system for your articles system. But I'm having a problem, I don't really know what the error is saying at this point.
The error:
Illuminate\Database\Eloquent\MassAssignmentException
body
The comment model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
The post model:
<?php
namespace App;
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function addComment($body)
{
$this->comments()->create(compact('body'));
}
}
The route I made:
Route::post('/posts/{post}/comments', 'CommentsController#store');
The comments controller:
<?php
namespace App\Http\Controllers;
use App\Post;
class CommentsController extends Controller
{
public function store(Post $post)
{
$post->addComment(request('body'));
return back();
}
}
Thanks in advance!
Explanation of this error
This is a security feature of Laravel. It is designed to protect you against form manipulation when using mass assignments.
For example on a sign-up form: When you have an is_admin column in your database, a user simply could manipulate your form to set is_admin to true on your server, and therefore in your database. This security feature prevents that by using a whitelist to define safe fields.
How to fix that
You need to set a $fillable property on your model. It's value must be an array containing all fields that are safe to mass assignable (like username, email address, ...).
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
# This property!
protected $fillable = ['body'];
// ...
}
See "Mass assignment" in the docs:
https://laravel.com/docs/5.5/eloquent#mass-assignment
Mass assignment is when you send an array to the model creation, basically setting a bunch of fields on the model in a single go, rather than one by one, something like what you did here:
public function addComment($body)
{
$this->comments()->create(compact('body'));
}
You need to add the field you are populating to the fillable array in Comments.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = ['body'];
public function post()
{
return $this->belongsTo(Post::class);
}
}
As the documentation states:
You may also use the create method to save a new model in a single
line. The inserted model instance will be returned to you from the
method. However, before doing so, you will need to specify either a
fillable or guarded attribute on the model, as all Eloquent models
protect against mass-assignment by default.
Hope this helps you.
I'm new to Laravel, and using Laravel 5 i'm having trouble returning an array from my database.
I have several "acts", and each act has many "banners". Whenever I try to get output from my array of banners ( $act->banners->count() ), i find it throws an error because it is null.
Here is the code:
routes.php:
Route::model('banners', 'Banner');
Route::model('acts', 'Act');
// Controller routes
Route::resource('acts', 'sf_ActController');
Route::resource('acts.banners', 'sf_BannerController');
Route::bind('banners', function($value, $route) {
return App\Banner::whereact_id($value)->first();
});
Route::bind('acts', function($value, $route) {
return App\Act::whereact_id($value)->first();
});
Act.php (model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Act extends Model
{
protected $table = 'sf_act';
protected $primaryKey = 'act_id';
public function act() {
return $this->hasMany('Banner');
}
}
Banner.php (model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Banner extends Model
{
protected $table = 'sf_banner';
protected $primaryKey = 'banner_id';
public function banner() {
return $this->belongsTo('Act' , 'act_id' , 'act_id');
}
}
sf_ActController.php (controller)
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Act;
use App\Banner;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use Redirect;
class sf_ActController extends Controller
{
public function show(Act $act)
{
//pass object to correct view
return view('pages.acts.show' , compact('act'))->with('banner', Banner::find($act));
}
acts/show.blade.php (view)
<!-- /resources/views/acts/show.blade.php -->
#extends('app')
#section('content')
<h2>{{ $act->act_title }}</h2>
{{ $act->banners->count() }}
at this point I get the following error:
FatalErrorException in a03036ad81fb4e6d90e9fe5e3da62c65 line 7:
Call to a member function count() on null
Why am I not fetching my banner data!? (The title variable in the h2 tags outputs fine, so the db and everything up until that point is working.)Thanks.
You need to specify the complete "route" to the model in the relationships including the namespace:
public function act() {
return $this->hasMany('App\Banner');
}
And the same on belongsTo:
public function banner() {
return $this->belongsTo('App\Act' , 'act_id' , 'act_id');
}
Could be a good idea to include the name of the foreign kay in the hasMany method.
public function act() {
return $this->hasMany('App\Banner', 'act_id');
}
Also possibly you don't need to include the third parameter in the belongs to.
Hope it helps. Also can share with you a link to learn about Laravel step-by-step: Learn Laravel 5.0 => 5.1
You currently have your hasMany relationship setup like this:
public function act() {
return $this->hasMany('Banner');
}
However in your view your calling this relationship:
$act->banners->count()
Shouldn't it be:
$act->act()->count();