Laravel eloquent save - laravel

I am trying to change a value on save
public static function boot()
{
static::saving(function ($formRow) {
$formRow->sales = 1;
});
}
But the weird part is that its not changing the sales to 1, any idea why ?

You're missing the call to the parent's boot method:
public static function boot()
{
// add this
parent::boot();
static::saving(function ($formRow) {
$formRow->sales = 1;
});
}

You can just override the save method on the model itself:
public function save(array $options = [])

Related

Laravel - Instantiate object and keep it within all controller's methods

I'm working with this case where I need to instantiate an object after a form is submitted in a controller. Everything's working fine until I call this object (as a property) from another method. It appears to be null.
If I intentiate the object from constructor method, I have no problem at all.
I can't keep this object in session because of closure.
Here's what i got so far.
// Version with the object iniate within the constructor that's working
class SearchConsoleController extends Controller
{
private $console;
protected function __construct() {
$callback = route('searchconsole.callback') ;
$this->console = $this->setConsole(env('CLIENT_ID'), env('CLIENT_SECRET'), $callback);
}
private function setConsole($cliendId, $cliendSecret, $callback){
$console = new Console(new Google_Client(), $cliendId, $cliendSecret, $callback);
return $console;
}
public function index(Request $request) {
return view('searchconsole.index')->with('authUrl', $this->console->getAuthUrl());
}
public function callback(Request $request){
if ($request->has('code')) {
$this->console->acceptCode($request->get('code'));
return redirect()->action('SearchConsoleController#listSites', [$request]);
}
else{
die('error');
}
}
Now the version which i'm stucked wih
class SearchConsoleController extends Controller
{
private $console;
private $callback;
protected function __construct() {
$this->callback = route('searchconsole.callback') ;
}
private function setConsole($cliendId, $cliendSecret, $callback){
$console = new Console(new Google_Client(), $cliendId, $cliendSecret, $this->callback);
return $console;
}
public function index(Request $request) {
// VIEW WITH A FORM FROM WHICH I GET CLIENT_SECRET & CLIENT_ID var
return view('searchconsole.index');
}
public function getAuthUrl(Request $request) {
// FORM FROM INDEX IS SUBMITTED
$clientId = ($request->has('google-client-id')) ?
$request->get('google-client-id') :
null
;
$clientSecret = ($request->has('google-client-secret')) ?
$request->get('google-client-secret') :
null
;
$this->console = $this->setConsole($clientId, $clientSecret, $this->callback);
return $this->console->getAuthUrl();
}
public function callback(Request $request){
if ($request->has('code')) {
// ***** MY PROBLEM *********
$this->console->acceptCode($request->get('code')); // HERE $this->console IS NULL;
// *******************
return redirect()->action('SearchConsoleController#listSites', [$request]);
}
else{
die('error');
}
}
I just can't figure out how I can do this so console is still available
UPDATE :
following #iamab.in advice, i looked into Service Provider but i just dont know how i can instante the Console Object within the service provider.
Here's what i've done.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Helpers\Console;
use Google_Client;
use Illuminate\Support\Facades\Route;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->app->bind(Console::class, function() {
$request = app(\Illuminate\Http\Request::class);
$clientId = ($request->has('google-client-id')) ?
$request->get('google-client-id') :
null
;
$clientSecret = ($request->has('google-client-secret')) ?
$request->get('google-client-secret') :
null
;
$callback = Route::get()->name('searchconsole.callback');
return new Console(new Google_Client(), $clientId, $clientSecret, $callback);
});
}
public function boot(){}
....
I just dont know how and where to implement it.
Thanks again
Update#2 :
okay my solution was working, I just didnt launch the correct app ..... 😅

Laravel Observer not triggered on UpdateorCreate

I have Model Model1 where I want to update a particular column rank on saved.
protected static function boot()
{
parent::boot();
static::saved(function ($model) {
$service = new Service();
$service->updateRank($model->id);
});
}
I put a log inside the saved. but it is not called
You should use method booted.
protected static function booted()
{
static::saved(function ($model) {
$service = new Service();
$service->updateRank($model->id);
});
}

Passing shared variable after login with Laravel 5.5

i created a method in order to share datas with all views of my application.
For this i created a class EntityRepository where i store the datas I want to share with all views.
Those data are displayed in the layout NOT the view.
class EntityRepository
{
use App\Valuechain;
public function getEntities()
{
$vcs = Valuechain::select('valuechains.id', 'lang_valuechain.vcname', 'lang_valuechain.vcshortname')
->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
->where('langs.isMainlanguage', '=', '1')
->whereNull('valuechains.deleted_at')
->get();
return $vcs;
}
}
When I want to send datas to the methods I simply call the getEntities() method... For example :
public function index(EntityRepository $vcs)
{
$entitiesLists = $vcs->getEntities();
// My code here ...
return view('admin.pages.maps.sectors.index', compact('entitiesLists', 'myVars'));
}
In this specific case it works fine and i don't have issue. My issue concerns the landing page after login.
In the loginController :
I defined the redirectTo variable this way :
public $redirectTo = '/admin/home';
For specific reasons I had to override the authentificated() method in the LoginController in order to check if my app is configured or need to be setup ...
protected function authenticated(Request $request, $user)
{
$langCount = Lang::count();
if ($langCount == 0) {
return redirect()->to('admin/setup/lang');
}
else {
//return redirect()->to('admin/home');
return redirect()->action('BackOffice\StatsController#index');
}
}
The concerned index() method is sending the variable onto the view :
public function index(EntityRepository $vcs)
{
$entitiesLists = $vcs->getEntities();
return view('admin.home', compact('entitiesLists'));
}
Whatever the return i make i have error message...
Undefined variable: entitiesLists (View: C:\wamp64\www\network-dev\resources\views\admin\partials\header-hor-menu.blade.php)
I finally solved this issue by changing my routes :
Route::group(['prefix' => 'admin'], function () {
Route::get('/', function (){
$checkAuth = Auth::guard('admin')->user();
if ($checkAuth) {
return redirect('/admin/main');
}
else {
return redirect('admin/login');
}
});
});
In my loginController i changed :
public $redirectTo = '/admin/home';
to :
public $redirectTo = '/admin/main';
Finally :
protected function authenticated(Request $request, $user)
{
$langCount = Lang::count();
if ($langCount == 0) {
return redirect()->to('admin/setup/lang');
}
else {
return redirect()->to('admin/main');
}
}

Laravel Model binding including SoftDeleted values

I have a Route::resource('sheeps', 'SheepsController') with a show function returning a resource:
public function show(Sheep $sheep)
{
return new SheepResource(
$sheep->load('farm')
);
}
So when I call /api/sheeps/123 should I get Sheep 123, but... I don't get it, because it's softdeleted.
How to fix the resource that it also searches in softdeleted results?
You should use this :
in your RouteServiceProvider :
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
parent::boot();
Route::bind('sheep', function ($value) {
return Sheep::withTrashed()->find($value);
});
}
Try this:
public function show($id)
{
$sheep = Sheep::withTrashed()->findOrFail($id);
and update your route
or
public function show(int $sheep)
{
$sheep = Sheep::withTrashed()->findOrFail($sheep);
or
use Explicit Binding

laravel model event static call issue

Why my static method don´t work with a varible class?
/**
* Events
*/
public static function boot() {
parent::boot();
$class = get_called_class(); // The value os $class is: Product ( string)
// This work
Product::creating(function($model) {
return $model->validate();
});
// Don´t work, the closure never called!
$class::creating(function($model) {
return $model->validate();
});
$class::updating(function($model) {
return $model->validate(true);
});
}
Incredible, this work to:
$class = "Product"; //get_called_class();
Solution ( Not elegant , but ... )
On my Product model i put this, to share class name with Base model.
public static function boot() {
parent::$cls = "Product";
parent::boot();
}
but updating does not work yet!
Actually (since PHP 5.3) it should work to do:
$class = 'Product';
$class::creating(function($model){
return $model->validate();
});
But why not just use static:: to access the current class? This way you don't need get_called_class:
static::creating(function($model){
return $model->validate();
});
There's also call_user_func if everything else fails...

Resources