I want to delete an item but I got this error message:
(1/1) MethodNotAllowedHttpException
in RouteCollection.php line 255
at RouteCollection->methodNotAllowed(array('PUT', 'DELETE'))
my routes:
Route::group(['prefix' => '/Seller', 'middleware' => ['seller_access']], function () {
Route::get('/','Seller\SellerController#index')->name('seller');
Route::group(['prefix' => '/Products'], function () {
Route::get('/', 'MarketingBundle\Seller\Product\ProductController#index')->name('marketing.seller.product.index');
Route::delete('/{id}', 'MarketingBundle\Seller\Product\ProductController#delete')->name('marketing.seller.product.delete');
Route::put('/{id}', 'MarketingBundle\Seller\Product\ProductController#update')->name('marketing.seller.product.update');
});
my url:
Seller/Products/228
my controller:
class ProductController extends Controller
{
public $resources = "marketing.seller.product";
public function index(Request $request)
{
$products = \Auth::user()->sellerProduct()->paginate(10);
return view($this->resources . '.index', [
'products' => $products
]);
}
/**
* #param $product_id
* #return \Illuminate\Http\JsonResponse
*/
public function delete($product_id)
{
dd("masoud");
\Auth::user()->sellerProduct()->detach(['product_id' => $product_id]);
return response()->json(['status' => true]);
}
re-order your routes like this.
Route::delete('/{id}', 'MarketingBundle\Seller\Product\ProductController#delete')->name('marketing.seller.product.delete');
Route::put('/{id}', 'MarketingBundle\Seller\Product\ProductController#update')->name('marketing.seller.product.update');
Route::get('/', 'MarketingBundle\Seller\Product\ProductController#index')->name('marketing.seller.product.index');
In order for laravel to know you're sending a patch or delete request you need to add a method field into your forms.
<form method='POST' action='#'>
#csrf
{{ method_field('PATCH') }}
</form>
Documentation
https://laravel.com/docs/5.7/helpers#method-method-field
https://laravel.com/docs/5.0/routing#method-spoofing
Related
I would like to know how can i pass the data in my database and display it in Welcome.blade.php i already have a data but i can't make it display in this view
this is my code in HomeController.php.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
}
public function index()
{
return view('home');
}
}
and this is my code in web.php, see that i am using HomeController#index
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
}
public function index()
{
return view('home');
}
}
now in my Welcome.blade.php i want to display the data in my database and my code right now is this.
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
#foreach($posts ?? '' as $post)
<div class="card-header">
{{$post->title}}
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
and this is my web.php code
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('about', function () {
return view('about');
})->middleware('checking');
Auth::routes(['register' => false]);
Route::group(['middleware' => 'auth'], function(){
Route::get('/home', [
'uses' => 'HomeController#index',
'as' => 'home'
]);
Route::get('/post/create', [
'uses' => 'PostsController#create',
'as' => 'post.create'
]);
Route::post('/blogs/store', [
'uses' => 'PostsController#store',
'as' => 'blogs.store'
]);
Route::get('/blogs/delete/{id}', [
'uses' => 'PostsController#destroy',
'as' => 'blogs.delete'
]);
Route::get('/blogs/edit/{id}', [
'uses' => 'PostsController#edit',
'as' => 'blogs.edit'
]);
Route::post('/blogs/update/{id}', [
'uses' => 'PostsController#update',
'as' => 'blogs.update'
]);
Route::get('/posts', [
'uses' => 'PostsController#index',
'as' => 'posts'
]);
});
Route::get('register', function () {
return redirect('/home');
});
also this is my Post.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'title','content','featured'
];
public function getFeaturedAttribute($featured) {
return asset($featured);
}
}
but why am i getting this kind of error?
Invalid argument supplied for foreach()(View: C:\xampp\htdocs\porge\dev\resources\views\welcome.blade.php)
Alright.
this is what I see.
you want to display the data in the welcome view which is loaded directly in your routes without passing any data.
Route::get('/', function () {
return view('welcome');
});
=> My suggestions:
The Common way to pass data is to use a controller. So you can use in your case, the HomeController or create a WelcomeController (what I will use next) .
Your public index function in the WelcomeController
public function index()
{
$posts = Post::all();
return view('welcome')->with('posts', $posts);
}
Your route for /
Route::get('/', [
'uses' => 'WelcomeController#index',
'as' => 'welcome_page'
]);
And then you loop the post like that in the welcome view
#foreach($posts as $post)
<div class="card-header">
{{$post->title}}
</div>
#endforeach
hopefully that helps.
I see several problem here. And yes, you should post your web.php part that matters for this request. Assuming your table for 'posts' has a model called Post
public function index()
{
$posts = Post::all();
return view('home', compact('posts'));
}
In your blade:
<div class="card">
<div class="card-body">
<ul class="list-group">
#foreach($posts as $post)
<li class="list-group-item">
{{$post->title}}
</li>
#endforeach
</ul>
</div>
</div>
That'll look a lot cleaner, don't you think?
What I'm trying to do is group multiple prefixes with one middleware:
Route::group(['middleware' => ['centralize']], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setLocale()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setCountry()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setCity()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setArea()], function () {
//routes
});
});
});
});
});
I have added the centralize middleware to kernel:
protected $routeMiddleware = [
...
'centralize'=> \App\Http\Middleware\Centralize::class,
...
];
But the middleware is not being called at all, is there is something missing here?
EDIT: it goes directly to the view of the home, I am doing dd inside of the middleware but it never reaches there!
EDIT: middleware code:
<?php
namespace App\Http\Middleware;
use App\Utilities\Centralization;
use Closure;
use Illuminate\Http\RedirectResponse;
class Centralize
{
/**
* #var \Illuminate\Http\Request
*/
private $request;
/**
* #var array
*/
private $params;
private $location;
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(\Illuminate\Http\Request $request, Closure $next)
{
$this->request = $request;
dd('hit');
$this->params = explode('/', $request->getPathInfo());
$this->figureLocale();
$this->figureCountry();
$this->figureCity();
$this->figureArea();
$this->figureLocation();
$redirection = implode('/', $this->params);
if ($request->getPathInfo() !== $redirection) {
return new RedirectResponse($redirection, 302, ['Vary' => 'Accept-Language']);
}
\View::share([
'countries' => Centralization::getCountries(),
'cities' => Centralization::getCities(),
'areas' => Centralization::getAreas(),
'location' => $this->location
]);
return $next($request);
}
private function figureLocale()
{
//...
}
private function figureCountry()
{
//..
}
private function figureCity()
{
//...
}
private function figureArea()
{
//...
}
private function figureLocation()
{
//...
}
}
EDIT: I also have tried:
Route::middleware(['centralize'])->group(function () {
Route::group(['prefix' => \App\Utilities\Centralization::setLocale()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setCountry()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setCity()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setArea()], function () {
//..
});
});
});
});
});
But with the same result , it never hits the middleware!
EDIT: clearing cache using artisan and manual doesn't work either!
Group route middleware called like this:
In routes/web.php
Route::group(['middleware' => ['centralize']], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setLocale()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setCountry()], function () {
//routes
});
});
});
In app/Http/kernal.php
protected $routeMiddleware = [
'centralize' => \App\Http\Middleware\CentralizeMiddleware::class,
];
In app/Http/Middleware/CentralizeMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CentralizeMiddleware
{
public function handle($request, Closure $next)
{
if (//Your Condition) {
//If true
}
else {
return $next($request);
}
}
}
You mentioned in one edit that:
it goes directly to the view of the home
So the URL you are visiting is actually /. And as clarified in the comments, the "home" route was defined nested inside the prefixes. But that means it is really a route for something like /fr/france/paris/somewhere/, and not a route for /.
The prefix in the route means "this route applies to URIs with this prefix". If a URI does not include that prefix, this routing is not applied.
So that means there is no route for /, and visiting it will:
not fire the centralize middleware;
not find a matching route, so throw a 404;
If you want to apply your centralize middleware to your home route, you'll need to place it inside that group, but outside the prefixes:
Route::middleware(['centralize'])->group(function () {
Route::get('/', 'HomeController#index')->name('home');
Route::group(['prefix' => \App\Utilities\Centralization::setLocale()], function () {
// ...
});
});
this is my web route php:
Route::get('settings', 'Settings\SettingsController#edit')->name('admin.settings.edit');
and I call this route name like below:
<a href="{{ route('admin.settings.edit') }}" class="nav-link ">
<span class="title">Settings</span>
</a>
but I got this error:
Route [admin.settings.edit] not defined. (View:
C:\xampp7\htdocs\template\resources\views\layouts\admin\sidebar.blade.php)
(View:
C:\xampp7\htdocs\template\resources\views\layouts\admin\sidebar.blade.php)
(View:
C:\xampp7\htdocs\template\resources\views\layouts\admin\sidebar.blade.php)
rouet:list returns this error message: `Class App\Http\Controllers\Admin\Settings\SettingsController does not exist
but I have this controller:
namespace App\Http\Controllers\Admin\SettingsController;
use App\Http\Controllers\Controller;
use App\Shop\Brands\Repositories\BrandRepository;
use App\Shop\Brands\Repositories\BrandRepositoryInterface;
use App\Shop\Brands\Requests\CreateBrandRequest;
use App\Shop\Brands\Requests\UpdateBrandRequest;
class SettingsController extends Controller
{
public function __construct(){}
public function index()
{}
public function create(){}
public function store(){}
/**
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit()
{
dd("milad");
return view('admin.brands.edit', ['brand' => '']);
}
/**
* #param UpdateBrandRequest $request
* #param $id
*
* #return \Illuminate\Http\RedirectResponse
* #throws \App\Shop\Brands\Exceptions\UpdateDiscountCodesErrorException
*/
public function update(UpdateBrandRequest $request, $id)
{
// $brand = $this->brandRepo->findBrandById($id);
//
// $brandRepo = new BrandRepository($brand);
// $brandRepo->updateBrand($request->all());
//
// return redirect()->route('admin.brands.edit', $id)->with('message', 'Update successful!');
}
public function destroy()
{}
}
`
updated
all my web route php:
/**
* Admin routes
*/
Route::namespace('Admin')->group(function () {
Route::get('admin/login', 'LoginController#showLoginForm')->name('admin.login');
Route::post('admin/login', 'LoginController#login')->name('admin.login');
Route::get('admin/logout', 'LoginController#logout')->name('admin.logout');
});
Route::group(['prefix' => 'admin', 'middleware' => ['employee'], 'as' => 'admin.' ], function () {
Route::namespace('Admin')->group(function () {
Route::group(['middleware' => ['role:admin|superadmin|clerk, guard:employee']], function () {
Route::get('/', 'DashboardController#index')->name('dashboard');
Route::namespace('Products')->group(function () {
Route::resource('products', 'ProductController');
Route::get('remove-image-product', 'ProductController#removeImage')->name('product.remove.image');
Route::get('remove-image-thumb', 'ProductController#removeThumbnail')->name('product.remove.thumb');
});
Route::namespace('Customers')->group(function () {
Route::resource('customers', 'CustomerController');
Route::resource('customers.addresses', 'CustomerAddressController');
});
Route::namespace('Categories')->group(function () {
Route::resource('categories', 'CategoryController');
Route::get('remove-image-category', 'CategoryController#removeImage')->name('category.remove.image');
});
Route::namespace('Orders')->group(function () {
Route::resource('orders', 'OrderController');
Route::resource('order-statuses', 'OrderStatusController');
Route::get('orders/{id}/invoice', 'OrderController#generateInvoice')->name('orders.invoice.generate');
});
Route::resource('addresses', 'Addresses\AddressController');
Route::resource('countries', 'Countries\CountryController');
Route::resource('countries.provinces', 'Provinces\ProvinceController');
Route::resource('countries.provinces.cities', 'Cities\CityController');
Route::resource('couriers', 'Couriers\CourierController');
Route::resource('attributes', 'Attributes\AttributeController');
Route::resource('attributes.values', 'Attributes\AttributeValueController');
Route::resource('brands', 'Brands\BrandController');
Route::resource('discounts', 'DiscountCodes\DiscountCodesController');
Route::resource('comments', 'Comments\CommentsController');
Route::resource('messages', 'Messages\MessagesController');
Route::resource('pages', 'Pages\PagesController');
Route::resource('blog-categories', 'BlogCategories\BlogCategoriesController');
Route::resource('blog-posts', 'BlogPosts\BlogPostsController');
Route::resource('scores-categories', 'ScoresCategories\ScoresCategoriesController');
Route::resource('scores-levels', 'ScoresLevels\ScoresLevelsController');
Route::resource('affiliate-categories', 'AffiliateCategories\AffiliateCategoriesController');
Route::resource('products-codes', 'ProductsCodes\ProductsCodesController');
Route::get('settings', 'SettingsController#edit')->name('admin.settings.edit');
});
Your controller namespace is wrong.
namespace App\Http\Controllers\Admin\SettingsController;
Change it to:
namespace App\Http\Controllers\Admin\Settings;
and your route to:
Route::get('settings', 'Admin\Settings\SettingsController#edit')->name('admin.settings.edit');
is it possible to pass id through an link href in Laravel and display that page like /projects/display/2.
I have this link:
<td>View</td>
It displays the id when hovering over the link as /projects/display/2. But whenever i click on the link i get an error message of:
Sorry, the page you are looking for could not be found.
I have a view setup called projects/display, plus routes and controller.
routes:
<?php
Route::group(['middleware' => ['web']], function (){
Route::get('/', 'PagesController#getIndex');
Route::get('/login', 'PagesController#getLogin');
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::get('/projects/display', 'ProjectsController#getDisplay');
Route::resource('projects', 'ProjectsController');
});
Controller:
<?php
namespace App\Http\Controllers;
use App\project;
use App\Http\Requests;
use Illuminate\Http\Request;
use Session;
class ProjectsController extends Controller
{
public function index()
{
}
public function create()
{
return view('projects.create');
}
public function store(Request $request)
{
$this->validate($request, array(
'name' => 'required|max:200',
'description' => 'required'
));
$project = new project;
$project->name = $request->name;
$project->description = $request->description;
$project->save();
Session::flash('success', 'The project was successfully created!');
return redirect()->route('projects.show', $project->id);
}
public function show()
{
$project = Project::all();
return view('projects.show')->withProject($project);
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function getDisplay($id){
$project = Project::find($id);
return view('projects/display')->withProject($project);
}
}
You need to change your route to:
Route::get('/projects/display/{id}', 'ProjectsController#getDisplay');
And then generate URL with:
{{ url('projects/display/'.$projects->id) }}
If you write route like below,
Route::get('/projects/display/{projectId}', 'ProjectsController#getDisplay')->name('displayProject');
You can use the name 'displayProject' in the href and pass the id as Array :
<td>View</td>
What you are looking for is a parameterized route. Read more about them here:
https://laravel.com/docs/5.3/routing#required-parameters
I found a better solution:
In your blade file do like this
<a href="{{route('displayProject',"$id")}}">
View
</a>
with this route , in route file
Route::get('/projects/display/{id}', 'ProjectsController#getDisplay');
$id is sent form your controller with compact
return view('viewPage', compact('id'));
So, i started with laravel. Tried with making a form post to the same page.
Here's what i have so far,
routes.php
Route::get('/', 'HomeController#showWelcome');
Route::group(array('before' => 'csrf'), function () {
Route::post('contactus', 'HomeController#sendEmail');
});
hello.php
<?php echo Form::open(array('action' => 'HomeController#sendEmail'))?>
input fields here
<?php echo Form::close() ?>
HomeController
public function showWelcome()
{
return View::make('hello');
}
public function sendEmail()
{
print_r($_POST);exit;
}
Problem: Form gets posted to the url public/contactus
Can someone point out which really stupid thing, i am doing?
routes.php
Route::get('/', 'HomeController#showWelcome');
Route::post('/', array(
'before' => 'csrf', // csrf filter
'uses' => 'HomeController#sendEmail' // the controller action to be used
));
hello.php
<?php echo Form::open(array('action' => 'HomeController#sendEmail')) ?>
<!-- input fields here -->
<?php echo Form::close() ?>
HomeController.php
Public function showWelcome()
{
return View::make('hello');
}
public function sendEmail()
{
$data = Input::all();
print_r($data);
// return the same view but with posted fields in the $data array
return View::make('hello', $data);
}
Routes
Route::get('/', 'HomeController#showWelcome');
Route::post('/', 'HomeController#sendEmail');
Hello.blade.php
#if(isset($post))
{{$post}}
#endif
{{Form::open()}}
{{Form::text('sometext')}}
{{Form::close()}}
HomeController
Public function showWelcome()
{
return View::make('hello');
}
public function sendEmail()
{
$post = Input::all();
return View::make('hello', array('post' => $post));
}