Return 404 in Laravel RouteServiceProvider - laravel

I want to give a 404 response if index.php is found in the url.
example url is domain.com/index.php/about
expected :
return blade 404
I've tried this code but can't get the 404 display
class RouteServiceProvider extends ServiceProvider
{
protected $namespace = 'App\Http\Controllers';
public function boot()
{
parent::boot();
}
public function map()
{
$this->removeIndexPhpFromUrl();
}
protected function removeIndexPhpFromUrl()
{
$currentUrl = url()->current();
if(strpos($currentUrl, 'index.php') !== false){
return view('errors.404');
}
}
}

I use this code for solving this problem
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\File;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use App\Foundation\Support\Collectable;
class RouteServiceProvider extends ServiceProvider
{
protected $namespace = 'App\Http\Controllers';
public function boot()
{
parent::boot();
}
public function map()
{
$this->removeIndexPhpFromUrl();
}
protected function removeIndexPhpFromUrl()
{
$currentUrl = url()->current();
if(strpos($currentUrl, 'index.php') !== false){
$url = str_replace('/index.php','', $currentUrl);
return redirect()->to($url)->send();
}
}
}
But I can't use abort(404) in this RouteServiceProvider.php

Related

Laravel : need a controller to be called on all views

What i want is to load a sidebar with a controller inside, on my layouts/app.blade.php.
i have read that the best way is to load it on AppServiceProvider, so i tried this :
View::composer('layouts.app', function ($view) {
$data = \App\Http\Controllers\DeliveryController::index();
$view::share('Delivery',$data);
});
That works, but the DeliveryController::index gave me this error :
Using $this when not in object context
The way that really works is to forget the AppServiceProviers and to do it on every views controller like this :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Management\DeliveryManagement;
class WelcomeController extends Controller
{
protected $deliveryManagement;
protected $nbLastsDelivery = 3;
public function __construct(DeliveryManagement $deliveryManagement)
{
// $this->middleware('auth');
$this->deliveryManagement = $deliveryManagement;
}
public function index()
{
$deliveries = $this->deliveryManagement->getLasts($this->nbLastsDelivery);
return view ('welcome', compact('deliveries'));
}
}
Unfortunately i think AppServiceProviers is a better way, right ?
If someone can help me i would be very grateful !
EDIT :
I add code of DeliveryController and DeliveryManagement :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\DeliveryRequest;
use App\Management\DeliveryManagement;
class DeliveryController extends Controller
{
protected $deliveryManagement;
protected $nbLasts = 3;
public function __construct(DeliveryManagement $deliveryManagement)
{
$this->deliveryManagement=$deliveryManagement;
}
public function index()
{
$deliveries=$this->deliveryManagement->getLasts($this->nbLasts);
return $deliveries;
}
and :
<?php
namespace App\Management;
use App\Models\Delivery;
class DeliveryManagement extends ResourceManagement
{
protected $delivery;
public function __construct (Delivery $delivery)
{
$this->model=$delivery;
}
public function getLasts($limit)
{
$req = $this->model->orderBy('deliveries.id', 'desc')->skip(0)->take($limit)->get();
$i=0; $render = array();
foreach($req as $delivery)
{
if($i=0)
$render = [$delivery, 'latest'];
else
$render = [$delivery, 'older'];
$i++;
}
return $render;
}
}

Laravel make validation request not working

When i submit the form is nothing happens.
here is my step.
php artisan make:request PostRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title'=>['required','max:255'],
'article'=>['required'],
'image'=>['image']
];
}
public function messages()
{
return [
'title.required'=>['need title'],
'article.required'=>['need article'],
];
}
}
?>
App/Http/Controllers/PostController.php
<?php
namespace App\Http\Controllers;
use App\Post;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\PostRequest;
use Illuminate\Support\Facades\Auth;
class PostController extends Controller
{
public function store(PostRequest $request)
{
Post::create($request->all());
return redirect()->route('post.index');
}
}
?>
If i don't use PostRequest it work perfectly,like this.
app/Http/Controllers/PostController.php
public function store(Request $request)
{
$post=new Post;
$post->user_id=Auth::user()->id;
$post->title=$request->title;
$post->article=$request->article;
$post->image=$request->image;
$post->save();
return redirect()->route('post.index');
}
And i missing something step?
Thanks everyone.
Your rules() function has a return array.
public function rules()
{
return [
'title'=>['required','max:255'],
'article'=>['required'],
'image'=>['image']
];
}
Change it to
public function rules()
{
return [
'title'=>'required|max:255',
'article'=>'required',
'image'=>'image'
];
}

Laravel and Local Tunnel integration

My idea was to use Local Tunnel's subdomain feature to expose callback URI in a more convenient way. However, I believe that I could've achieved the same results in a simper way.
This is the solution with Laravel Valet:
In package.json I've added a script called shared
"scripts": {
...
"share": "lt --port 80 --subdomain blog --local-host blog.test"
}
In AppServiceProvider.php I've extended the UrlGenerator to avoid redirecting back to http://blog.test
<?php
namespace App\Providers;
use App\Services\LocalTunnelUrlGenerator;
use Blade;
use Illuminate\Http\Resources\Json\Resource;
use Illuminate\Routing\Router;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
(...)
}
public function register()
{
$this->enableLocalTunnel();
}
private function enableLocalTunnel()
{
if (!app()->environment('local') || !config('app.use_local_tunnel')) {
return;
}
$this->app->extend('url', function (UrlGenerator $defaultGenerator) {
/** #var Router $router */
$router = $this->app['router'];
$routes = $router->getRoutes();
return new LocalTunnelUrlGenerator($routes, $defaultGenerator->getRequest());
});
}
}
This is the the LocalTunnelUrlGenerator.php:
<?php
namespace App\Services;
use Illuminate\Http\Request;
use Illuminate\Routing\RouteCollection;
use Illuminate\Routing\UrlGenerator;
class LocalTunnelUrlGenerator extends UrlGenerator
{
public function __construct(RouteCollection $routes, Request $request)
{
parent::__construct($routes, $request);
}
public function formatRoot($scheme, $root = null)
{
return "https://blog.localtunnel.me";
}
}
Why all that? Because whenever the application call the redirect() method, we are sent back to http://blog.test.
Do I really need to extend the UrlGenerator to make it work?

Target [App\Http\Controllers\IndexController] is not instantiable. in laravel

I have cloned project from github and installed in my local system everything is working fine.
And i created controller through command, the controller is created but when i try to use controller function the error shows me like below.
BindingResolutionException
Target [App\Http\Controllers\SomeController] is not instantiable.
in Container.php (line 895)
I tried to solve this problem by running command below:
php artisan cache:clear
php artisan clear-compiled
composer dump-autoload
php artisan optimize
php artisan config:clear
But i still got same error. Kindly help me to resolve this issue.
My controller is:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SomeController extends Controller
{
public function getIndex() {
echo "string";
}
}
AppServiceProvider.php :
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
Controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Carbon\Carbon;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected function __construct() {
$variable2 = "I am Data 2";
View::share ( 'variable2', $variable2 );
}
protected function create_permission($role_type_id,$module_id)
{
$CheckCreatePermission = \DB::table('role_type_access')->where(['role_type_id'=> $role_type_id,'module_id'=>$module_id])->select('create')->get();
if(!empty($CheckCreatePermission[0]))
{
if($CheckCreatePermission[0]->create===1)
{
return 1;
}
return 0;
}
return 0;
}
protected function edit_permission($role_type_id,$module_id)
{
$CheckEditPermission = \DB::table('role_type_access')->where(['role_type_id'=> $role_type_id,'module_id'=>$module_id])->select('edit')->get();
if(!empty($CheckEditPermission[0]))
{
if($CheckEditPermission[0]->edit===1)
{
return 1;
}
return 0;
}
return 0;
}
protected function delete_permission($role_type_id,$module_id)
{
$CheckDeletePermission = \DB::table('role_type_access')->where(['role_type_id'=> $role_type_id,'module_id'=>$module_id])->select('delete')->get();
if(!empty($CheckDeletePermission[0]))
{
if($CheckDeletePermission[0]->delete===1)
{
return 1;
}
return 0;
}
return 0;
}
protected function view_permission($role_type_id,$module_id)
{
$CheckViewPermission = \DB::table('role_type_access')->where(['role_type_id'=> $role_type_id,'module_id'=>$module_id])->select('view')->get();
if(!empty($CheckViewPermission[0]))
{
if($CheckViewPermission[0]->view===1)
{
return 1;
}
return 0;
}
return 0;
}
protected function view_all_permission($role_type_id,$module_id)
{
$CheckLayoutPermission = \DB::table('role_type_access')
->join('modules', 'role_type_access.module_id', '=', 'modules.id')
->where(['role_type_access.role_type_id'=> $role_type_id,'role_type_access.view'=>1,'role_type_access.module_id'=>$module_id])
->select('role_type_access.module_id','role_type_access.view','role_type_access.create','role_type_access.edit','role_type_access.delete','modules.name','modules.label')->get();
return $CheckLayoutPermission;
// print_R($$CheckViewMenuPermission);
// echo count($CheckViewMenuPermission);
/* if(!empty($CheckViewPermission[0]))
{
if($CheckViewPermission[0]->view===1)
{
return 1;
}
return 0;
}
return 0;*/
}
public function getDownload($file_path,$file_name)
{
//PDF file is stored under project/public/download/info.pdf
$file= public_path().'/uploads/'.$file_path.'/'.$file_name;
$headers = array(
'Content-Type: application/pdf',
);
return \Response::download($file, $file_name, $headers);
}
public function updateTracker($tracked_date,$action)
{
$Globaltracks = \DB::table('global_tracks')->where('tracked_date', $tracked_date)->get();
if (count($Globaltracks) > 0) {
\DB::table('global_tracks')
->where('tracked_date', $tracked_date)
->increment($action,1,['updated_at'=>Carbon::now()->toDateTimeString()]);
} else {
$Globaltracks_id = \DB::table('global_tracks')->insert(
['tracked_date' => $tracked_date,$action => 1,'created_at'=>Carbon::now()->toDateTimeString()]);
}
}
}
Change Your Constructor Access Modifier to Public. It solve my problem.
public function __construct() {
$variable2 = "I am Data 2";
View::share ( 'variable2', $variable2 );
}
Update your SomeController with the below code:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class SomeController extends Controller
{
public function getIndex() {
echo "string";
}
}

laravel 5.4: seeding for inheritance model return error

I have created base model and extend all my model from base model in laravel 5.4. When i do db:seed i got error
Trying to get property of non-object
. Anyone know why it happens? it is db:seed did not support model inheritance.
Base Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
class BaseModel extends Model
{
public static function boot()
{
parent::boot();
static::creating(function($model)
{
$model->created_by = Auth::user()->id;
$model->updated_by = Auth::user()->id;
});
static::updating(function($model)
{
$model->updated_by = Auth::user()->id;
});
static::deleting(function($model)
{
$model->deleted_by = Auth::user()->id;
$model->save();
});
}
}
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\SoftDeletes;
class Bank extends BaseModel
{
use SoftDeletes;
public static function boot()
{
parent::boot();
}
}
Seeder:
<?php
use Illuminate\Database\Seeder;
use App\Bank as Bank;
class BanksTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Bank::create( [
'name' => 'xxxxxxxx' ,
] );
}
}
Probably it has to do with Auth::user()->id. db:seed is executed in terminal and has no authenticated user, therefore Auth::user() will return NULL. Do a check before setting created_by and updated_by.
static::creating(function($model)
{
if (Auth::user())
{
$model->created_by = Auth::user()->id;
$model->updated_by = Auth::user()->id;
}
});
Hope this helps :)

Resources