No query results error using artisan with object instantiated in service provider - laravel

I have created a service provider which provides a class App\Path. This is loaded up through Eloquent using $request->getPathInfo()
$this->app->singleton(Path::class, function($app)
{
$request = $app->make(\Illuminate\Http\Request::class);
$path = Path::with(['template', 'parts'])->findOrFail($request->getPathInfo());
return $path;
});
The app works fine and as expected. However when I want to use Artisan I get the following error:
In Builder.php line 369:
No query results for model [App\Path] /
This prevents me from clearing caches, creating models etc. It seems that Laravel runs register() when running any artisan command and when this done, the request path is "/" which doesn't exist in the DB. Is there a better way to populate the Path object? The only way to solve this seems to add a dummy record for "/".

You can check whether the app is running from console and adjust its logic, for example:
$this->app->singleton(Path::class, function($app)
{
if ($app->runningInConsole()) {
return null;
}
$request = $app->make(\Illuminate\Http\Request::class);
$path = Path::with(['template', 'parts'])->findOrFail($request->getPathInfo());
return $path;
});

Related

Laravel Nova - Observer Update Method Causes 502

When trying to update a resource in Laravel Nova that has a Observer the update loads for a while and then ends with a 502 error. The observer is registered correctly (the created method works fine) and I'm not trying to do anything special in the updated method. Any ideas?
public function updated(Model $model)
{
//
$model->title = 'test';
$model->save();
}
If I try this without the $model->save(), there is no 502 error but the change I want to happen also doesn't happen. I get the green success message, and any change I make on the form prior to updating occurs, but not the change I'm trying to make during the updated method.
Any help troubleshooting this would be appreciated
I am not very good at Laravel, but I think, that you should to try this:
In your model file add method:
public function saveQuietly(array $options = [])
{
return static::withoutEvents(function () use ($options) {
return $this->save($options);
});
}
Then, in your updated method in observer do something like this:
public function updated(Model $model)
{
$model->title = 'test';
$model->saveQuietly();
}

The update nor the destroy methods won't work in laravel eloquent model?

I have a strange situation where eloquent model won't let me update nor destroy while index and create is working fine!
I'm using Vue.js and Laravel API Resource for form control, and while it worked with me before, it won't work here:
Here's my Vue.js Code:
updateFinish(finish) {
axios.patch(`/api/finishes/${finish.id}`, finish).then(response => {
this.fetchFinishes();
}).catch(error => {
// Get laravel validation error
this.errors = error.response.data.errors;
});
},
laravel update code (not working)
public function update(FinishType $finishType)
{
// Don't know why not working
$finishType->update($this->validateRequest());
return new FinishTypeResource($finishType);
}
the response is null:
{"id":null,"name":null}
While this code works:
public function update($id)
{
$finishType = FinishType::find($id);
$validates = $this->validateRequest();
$finishType->name = $validates['name'];
$finishType->save();
return new FinishTypeResource($finishType);
}
public function validateRequest()
{
return request()->validate([
'name' => 'required | unique:finish_types',
]);
}
Note the Model name is FinishType and database table name is finish_types, I even tried to define the table name in the model like so protected $table = 'finish_types' – still not working and I already have defined the $fillable array!!!
Your route model binding is not working correctly, for the implicit binding to work your injected variable should match the route parameter name.
Assuming that your parameter name could be finish (reading the url from your javascript) you have to write the update function using $finish as injected variable, like this:
public function update(FinishType $finish)
{
$finish->update($this->validateRequest());
return new FinishTypeResource($finish);
}
Do the same for destroy():
public function destroy(FinishType $finish)
{
// your destroy code here
}
In any case you can run php artisan route:list to find your parameter name (the part of the URI in braces) and give the same name to the injected variable.
If the two do not match, parameter and injected variable name, laravel injects a void, not loaded, FinishType model so it does not make sense doing an update or a delete on it.
I can't post comments so I'm going to post what I assume is the answer.
Laravel does route model binding automagically when the route url name corresponds to the name of the table I think... or model.
So users/{id} would auto bind the User object when you type it as a param in the controller. Example (User $user)
However, since your URL seems to be "different" from the name of your Model/Table, go to the RouteServiceProvider, and manually do the binding.
So in your case you'd do something like this in the boot function of the RouteServiceProvider class:
public function boot()
{
parent::boot();
Route::model('finishes', FinishType::class);
}
Don't forget your imports :)
You can read more about Explicit Model Binding here: https://laravel.com/docs/5.8/routing#explicit-binding

Create custom cache drive in laravel 5.8 given error "Driver [aerospike] is not supported."

I wanted to create a custom cache driver using aerospike.
I have followed the instruction given in the document:
https://laravel.com/docs/5.8/cache#adding-custom-cache-drivers
Cache::extend('aerospike', function ($app) {
$config = $app['config'];
$server = $config['cache.stores.aerospike.servers'];
$aerospike = new \Aerospike($server);
$store = new AerospikeStore($aerospike, $config['cache.prefix'], $config['cache.stores.aerospike.namespace']);
return Cache::repository($store);
});
also created the AerospikeStore file.
When run php artisan serve it always says :
In CacheManager.php line 109:
Driver [aerospike] is not supported.

phpunit getContent return empty

I am learning Laravel 5.4, Still new to Laravel and PHPUnit. Everything is working great after following online basic tutorial.
This test function is working correctly when run phpunit
public function testBasicExample()
{
$response = $this->call( 'GET' , '/welcome');
$this->assertTrue(strpos($response->getContent(), 'Laravel') !== false);
}
Problem comes when I try to test Api
Steps I took
Create Api route for books
Return all users from users talbe as json from localhost/api/books/
public function index()
{
$users = DB::table('users')->get()->toJson();
echo $users;
}
I open the link in browser and json is returned correctly
copy and pasted json into online json validator jsonlint and it is valid.
Create a new test function
public function test_index_method_returns_all_books()
{
$response = $this->call( 'GET' , '/api/books/');
$this->assertEquals(200, $response->getStatusCode());
$data = json_decode($response->getContent(),true);
$this->assertJson($data);
}
run phpunit
200 status test passed but assertJson did not pass.
I tried to do var_dump for $response->getContent() and found out it return empty.
now I am not able to get getContent() for api/book/. Does anyone know if there is a solution for this?
Thanks.
Here is a screenshot
Try create some data with a factory before you call the api:
e.g.:
factory(\App\Books::class, 20)->create();
then
$response = $this->call( 'GET' , '/api/books/');
If you had set ":memory:" as your database on phpunit.xml, you will no longer see any data from your local database, that's why you should use factory instead.

Sessions in laravel 5.3 don't start

I am having problems with storing values in a session. I am using laravel 5.3 on xampp local host. I have tried the following but when I try to access the session is empty:
//using global session helper method
$variable = session(['exam'=>$exam]);
$exam = session('exam');
echo $exam; //exam is always empty
//I have also tried this
public function myControllermethod(Request $request)
{
$exam = $request->session()->put('exam',$exam);
//get the session
$exam = $request->session()->get('exam');
echo $exam // this approach returns the following exception
}
RuntimeException in Request.php line 905:
Session store not set on request.
I have tried both the file and database drivers without lack. Sessions are actually not being registered at all. Session::get('key') also do not work,
How can I start sessions in laravel 5.3. Any Help?

Resources