Issue in dynamic model loading in Laravel 5.6 - laravel

I am trying to load models dynamically in my controller based on route type. But when I run program I get a message saying "class not found". Here is my code and a link of stackoverflow which I used to fix my issue.
Code:
$model = $this->getModelName($request->matchType);
$class = "App\Models\$model";
if($model && class_exists($class))
{
$data = $class::where('type_id',$type)->firstOrFail();
}
else
{
$data = MyModel::find($type);
}
return $this->showOne($data);
Link:
Load in models dynamically in Laravel 5.1
This is a good link but not working for me and why simple $model::all() not working.

You need to use double backslashes:
$class = "App\\Models\\$model";
Try using the app helper to resolve the model:
$data = app($class)->where('type_id',$type)->firstOrFail();

Add another slash to your class name:
$class = "\App\Models\$model";
instead of :
$class = "App\Models\$model";

Related

Laravel 6.2 - Dynamically Call a Controller action

I have used a code from Internet to call controller action dynamically. Here is the code for that, and is used in web.php. But I dont fully understand what it does.
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
$params = explode('/', $params1);
$params[1] = $params2;
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
return $controller->callAction($action, $params);
})->middleware('supadminauth');
Can someone explain?
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
The first line looks at the request to see whether it is a get or post request, if it is some other types of request that means it does not match and will not proceed further. Then the url are separated into 4 parts corresponding by their name and passed into variables with the same name i.e. $controller, $action, $param1 and $params2 where the last 3 variables do not need to be present (with ? at the end of the name).
$params = explode('/', $params1);
$params[1] = $params2;
I believe this is a crude way to create an array of parameters as $params where the following would be more appropriate.
$params = [$params1, $params2];
.
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
Then load the relevant controller.
return $controller->callAction($action, $params);
And run the corresponding action and passing all the parameters with it.
Hope this makes sense.
This is example of use it:
If you have controller like bellow:
class AdminController extends Controller {
public function index(){ //sample 0, sample 1
...
}
public function view($param1){ //sample2 , sample3
...
}
}
There is some sample route for calling them
sample0: yoursite.com/admin
sample1: yoursite.com/admin/index
sample2: yoursite.com/admin/view
sample3: yoursite.com/admin/view/5
Notice in your question ? in {action?} means it can either have value or not. Other things is simple and clear. Do you need more explaination?

How can i get current module name [nwidart/laravel-modules]

How can i get current module name, or current namespace. of laravel
I use this library [nwidart/laravel-modules].
I trid this code but not solve problem
$module_name = basename(__FILE__, '.module');
To get module entity: $module = Module::find('blog');
To get module name: $module->getName();
This is documented pretty well by package author here:
https://nwidart.com/laravel-modules/v1/advanced-tools/module-methods
Add this to your modules __construct controller :
private $module_name;
public function __construct()
{
$class = get_called_class(); // or $class = static::class;
$arr_class = explode("\\", $class);
$this->module_name = $arr_class[1];
}
public function index()
{
echo $this->module_name;
}

Laravel unlink method

can someone tell me how to unlink image from public path when product is deleted.
My current code which does not work:
public function destroy($id)
{
$product = Product::findOrFail($id);
$image_path = '/uploads/products/' . $product->image;
if(file_exists($image_path)){
unlink($image_path);
}
$product->delete();
}
Also tried:
$product = Product::findOrFail($id);
if(file_exists($product->image)){
unlink($product->image);
}
$product->delete();
Also I am using accessor so my $product->image is returning:
"http://myeshop.local/uploads/products/1593902362bluesocksupd.jpg"
Here is accessor code:
public function getImageAttribute($image){
return asset($image);
}
use model deleted event
//Product Model
protected static function boot()
{
parent::boot();
static::deleted(function($product){
// getOriginal skip accessor
$image = public_path('uploads/products/' . $product->getOriginal('image'));
if(file_exists($image)) {
unlink($image);
}
});
}
unlink($path) is a PHP function. It will delete a file located at a local path. According to your question the value of $product->image is the complete URL to the image. If it is then the following is true:
$product = Product::findOrFail($id);
$image_path = '/uploads/products/' . $product->image;
// $image_path = '/uploads/products/http://myeshop.local/uploads/products/1593902362bluesocksupd.jpg'
// and it needs to point to '/PATH/TO/LARAVEL/uploads/products/1593902362bluesocksupd.jpg'
// the following file_exists() will return false
if(file_exists($image_path)){
unlink($image_path); // so you never get here
}
There are some quick and dirty ways to fix this, but the best thing to do is to have the $product->image property point to just the name of the file. Then in your view apply the file name to the /uploads/products/ directory on the web server.
Doing this will allow you to apply the /uploads/products/ local path and have a better time finding the file you want to delete. I'm assuming the uploads directory is in your Laravel public directory so you'd want to do something like this:
// $product->image must point to the filename only: 1593902362bluesocksupd.jpg
// The file_exists should evaluate to true and unlink() will work.
$image_path = public_path('uploads/products/' . $product->image);
if(file_exists($image_path)){
unlink($image_path);
}
In your Blade template view you'd need to show the product image using something like this:
<img src="{{ url('/uploads/products/' . $product->image) }}" />
Storing a complete URL in your database doesn't scale well if you wanted to develop another website or reuse this code on another project. This way you can let Laravel manage where the URL or local file system is.
You could use PHP's unlink() method.
But if you want to do it the Laravel way, use the Storage::delete method instead :
use Illuminate\Support\Facades\Storage;
public function destroy($id)
{
$product = Product::findOrFail($id);
$image_path = public_path('uploads/products/' . $product->image);
if(file_exists($image_path)){
Storage::delete($image_path);
}
$product->delete();
}

How to get all of name route in laravel

I going to get all of route name in laravel project.
For example :
I have this route :
Route::get('/home', 'HomeController#index')->name('homeNameRoute');
I want get homeNameRoute !!!
tanks.
Use the currentRouteName() method:
Route::currentRouteName();
This will return you homeNameRoute when you are on the /home page.
you can try this.. using Route Facade
$routes = Route::getRoutes();
dd($routes);
or try use Artisan::call
\Artisan::call('route:list');
\Aritisan::output();
Maybe this can be helpful:
$route_name = [];
foreach (Route::getRoutes()->getRoutes() as $route) {
$action = $route->getAction();
if (array_key_exists('as', $action)) {
$route_name[] = $action['as'];
}
}
dd($route_name);

Problems updating using Eloquent

Right now I'm working on my first update function using Eloquent ORM. Trying to follow the docs, I have this in my model:
public function updateAvailability()
{
$this->active = Input::get('available');
$this->activeDetails = Input::get('availableStatus');
$this->save();
}
which returns:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
and all of this is being called to in my controller as:
public function updateProfile($id)
{
if(Input::get('type')=='availability'){
$availability = User::find($id)->updateAvailability;
}
$name = str_replace(' ', '', Input::get('name'));
return Redirect::to('people/'.$name);
}
Are there some gaps in my understanding of updating in Eloquent? (I'm sure there are). I would love to use ajax to handle it, but I can't seem to find the right resources to get that working.
SOLVED: $availability = User::find($id)->updateAvailability; needed to be changed to $availability = User::find($id)->updateAvailability();. That's all.

Resources