This is create.blade.php file. In this include css and js file too..
Html code and ajax code view file
#extends('layouts.app')
#section('content')
<link rel="stylesheet" href="http://www.codermen.com/css/bootstrap.min.css">
<script src="http://www.codermen.com/js/jquery.js"></script>
<form enctype="multipart/form-data" method="post" action="{{route('post.store')}}" >
#csrf
<div class="form-group col-md-8">
Category<select name="category" id="category" class="form-control">
<option>select</option>
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->category}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-8">
Category<select name="subcategory" id="subcategory" class="form-control">
<option>select</option>
#foreach($subcategories as $subcategory)
<option value="{{$subcategory->id}}">{{$subcategory->subcategory}}</option>
#endforeach
</select>
</div>
</form>
#endsection
This is controller code which create function code of category and subcategory
public function create(Request $request){
$categories = Category::all();
$subcategories = DB::table('subcategories')
->where('category_id', $request->category_id)
->pluck('subcategory', 'id');
return view('post.create', compact('categories', 'subcategories'));
}
This is route
Route::get('/post/create', 'PostController#create')->name('post.create');
Problem is if i select category still no show related to subcategory
The jquery append code looks like it is correct. I think the problem may be in your routing.
You've got
url:"{{url('create')}}?category_id="+categoryID,
as a GET request called through the Laravel method url(). It might help if you use url() here in the way you've got the route setup in web.php, which would use the full url path:
url:"{{url('post/create/')}}"+categoryID,
This lets the url() function add the parameter. However, it might also help to account for the incoming parameter on your routes file if it is a GET request (and add $category_id to the controller method):
Route::get('post/create/{id}', 'PostController#create')
I would probably make a separate function just to get the subcategories - then make your ajax call to that function and just pull the subcategories. A little cleaner.
But I think your problem may be in the routing and perhaps some of the above will help you.
you have done silly mistake , you are sending ajax request on change of category select dropdown to your create function , while your create function is rendering view post.create instead of return json response to ajax request .
so now what you can do ? 2 options available to you :
option 1 : create other function named "get_subcategory_by_category_id" and that will return subcategories in json , also create new route in routes/web.php for same .
option 2 : laravel provide $request->ajax() to detect that request is ajax or not ? so use that and return response in json , so you will get response .
public function create(Request $request){
$categories = Category::all();
$subcategories = DB::table('subcategories')
->where('category_id', $request->category_id)
->pluck('subcategory', 'id');
if($request->ajax()){
$response=array('categories'=>$categories,'subcategories'=>$subcategories);
return response()->json($response,200);
}
return view('post.create', compact('categories', 'subcategories'));
}
your ajax function should be like below :
<script type="text/javascript">
$(document).on('change','#category',function(){
var categoryID = $(this).val();
if(categoryID){
$.ajax({
type:"GET",
url:"{{url('create')}}?category_id="+categoryID,
dataType:'json',
success:function(res){
if(res){
console.log(res);
// forloop through subcategory and append
}else{
$("#subcategory").empty();
}
}
});
}else{
$("#subcategory").empty();
}
});
</script>
make sure that your request url is proper , also check Inspect Element > Network tab for ajax request response .
Related
I'm using Laravel and I am currently implementing the 'destroy' method in a resource controller as part of CRUD. The method should delete the specified record in my database.
The method is called by my blade.php file, which uses a form with the DELETE method and route('my-resources.destroy', $my-resource->id). I want the controller to return a string such as 'Deleted successfully!' so that I can display that to the client.
Here is my code:
In views/book/edit.blade.php:
<form method="DELETE" action="{{ route('books.destroy', $book->id) }}">
<div class="form-item center">
<button type="submit" class="btn-danger">Delete</button>
</div>
</form>
and in BookController.php:
public function destroy($id)
{
$book = Book::find($id);
$book->delete();
return redirect()->away('https://www.google.com');
}
I put a redirect to google.com just to see if the redirect works, but it doesn't. When I click the 'Delete' button, the url changes from http://127.0.0.1:8000/books/1/edit to http://127.0.0.1:8000/books/1? with that question mark at the end. What am I doing wrong?
I have another question: if I want to return the status, should I use something like
Route::get('/', function () {
return 'Deleted successfully';
});
or
$request->session()->flash('status', 'Task was successful!');
/** and some random return statement **/
Thanks!
Forms do not support the DELETE method so you need to use the Laravel #method helper to tell Laravel you want to use the DELETE verb. Additionally, you need to include the csrf token that Laravel expects are part of preventing cross-site request forgeries.
<form action="{{ route('books.destroy', $book->id) }}" method="POST">
#csrf
#method("DELETE")
... // Button/link for submit this form
</form>
You may need to define your route so that it accepts a DELETE request, unless you have defined a resourceful route:
Route::delete('/books/{id}', 'BookController#destroy')
->name('books.destroy'); // Laravel 7
Route::delete('/books/{id}', [\App\Http\Controllers\BookController::class, 'destroy'])
->name('books.destroy'); // Laravel 8
If you're using resourceful routes, they will be made available for you already:
Route::resource('/books', 'BookController'); // Laravel 7
Route::resource('/books', \App\Controllers\Http\BookController::class); // Laravel 8
For your destroy method, set a flash message to be sent back:
public function destroy(Book $id)
{
$id->delete();
return redirect('/')->with('success', 'Book deleted');
}
Then flash the message in your view:
#if (session('success'))
<p>{{ session('success') }}</p>
#endif
I am creating ecommerce website in Laravel and I want to hide productdetails id in url. What can I change in code plz need solution.
Web.php
Route::get('/productdetail{id}','ProductDetailController#display_products_details');
controller code:
public function display_products_details($id)
{
$data = DB::select('select * from subcategory inner join product_details on subcategory.sub_id=product_details.sub_id where product_details.sub_id = ?',[$id]);
return view('productdetails',['data'=>$data]);
}
link tag code:
{{ $value->name_of_subcategory }}
path I getting:
localhost:8000/productdetail12
But actually I want Localhost:8000/productdetail
You can do this by having the id as part of the request body so it will not be visible in the URL (it will still be visible to anyone inspecting the request body via their browser developer tools).
You can do this by using a form to send a post request:
Route::post('/productdetail','ProductDetailController#display_products_details');
The link will change to a form:
<form method="POST" action="{{ action('ProductDetailController#display_products_details') }}>
#csrf
<input type="hidden" name="id" value="{{ $value->sub_id }}" />
<button type="submit">{{ $value->name_of_subcategory }}</button>
</form>
You may need to style the button to look like a link.
The controller becomes:
public function display_products_details(Request $request)
{
$request->validate([ 'id' => 'required|int' ]);
$id = $request->input('id');
$data = DB::select('select * from subcategory inner join product_details on subcategory.sub_id=product_details.sub_id where product_details.sub_id = ?',[$id]);
return view('productdetails',['data'=>$data]);
}
Note that while this is theoretically possible it does result in very bad user experience. People can't share product links with others for example
i am trying to make a list of locations that you can rent. but to rent the place you need to fill in some information. to fill in this information you excess another page. how do i make it so laravel knows the page belongs to a certain location
this is what ive done now but i keep getting the error:
Call to undefined method App\Reservation::location()
as soon as i have filled in the fields of information
this is the blade file that links to the the create reservation file
#foreach
($locations as $location => $data)
<tr>
<th>{{$data->id}}</th>
<th>{{$data->name}}</th>
<th>{{$data->type}}</th>
<th><a class="btn" href="{{route('Reservation.index', $data->id)}}">rent</a></th>
</tr>
#endforeach
this is the create reservations blade
<form action="{{ route('location.store') }}" method="post">
#csrf
<label>title</label>
<input type="text" class="form-control" name="name"/>
<label>type</label>
<select>
<option value="0">klein</option>
<option value="1">groot</option>
</select>
<button type="submit" class="btn">inschrijven</button>
</form>
this is what the location controller looks like
public function store(Request $request)
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($request->location());
$location->save();
return redirect('/location');
}
and the relationships in my models should also work
class Reservation extends Model
{
public function locations()
{
return $this->belongsTo('Location::class');
}
}
class Location extends Model
{
public function reservations()
{
return $this->hasMany('Registration::class');
}
}
ive been stuck at this all day and i really dont know where to look anymore
The error you are getting is because of the wrong function name, you are calling location, while it is locations.
public function locations(){}
&
$location->location()->associate($request->location());
and you can pass the variable as a query parameter, you'll need to pass this data as an array in your blade file.
Web.php
Route::get('/somewhere/{id?}, function(){
//do something
})->name('test');
Blade
route('test', ['id' => $id]);
Controller Method
public function store(Request $request, $id) //Adding the query parameter for id passed in Route.
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($id);
$location->save();
return redirect('/location');
}
I have a page that shows links with name of businesses that are retrieved in database like this:
Controller:
public function viewBusiness() {
// Return our "website" object
$business = Business::all();
// Pass the contents of the "html" property to the view
return view('viewBusiness', ['business' => $business]);
}
View:
#extends('master') #section('title', 'Live Oldham') #section('content')
#section('content')
#foreach ($business as $businesses)
<a target="_blank" href="{{ url('business/' . $businesses->name) }}"> {{($businesses->name) }}
</a> #endforeach
#endsection
Route:
Route::get('business/list', 'BusinessController#viewBusiness')->name('viewBusiness');
I then have added a function where user click on a link and it is taken to a page which displays all data for that specific business, however it diplays all data but for all businesses.
Controller:
function displayBusiness() {
$business = Business::all();
$address = Address::all();
return view('displayBusiness', ['business' => $business, 'address' => $address]);
}
View:
#foreach ($business as $businesses)
<p>{{$businesses->name}}</p>
<p>{{$businesses->email}}</p>
#endforeach
#foreach ($address as $addresses)
<p>{{$addresses->firstline_address}}</p>
<p>{{$addresses->secondline_address}}</p>
<p>{{$addresses->town}}</p>
<p>{{$addresses->city}}</p>
<p>{{$addresses->postcode}}</p>
<p>{{$addresses->telephone}}</p>
#endforeach
Route:
Route::get('business/{name}', 'BusinessController#displayBusiness')->name('displayBusiness');
Now here's the question, how can this code be modified so only a business that match either bussiness->name or business->id is displayed. (I guess name is taken when user clicks on a name.
Another question is how to restrict the url so that if localhost/business/{name} is not equal to any business->name in the database returns error? at the moment it shows the page no matter what you enter.
Thanks!
I do not know if I understood the question, but that may be the beginning of a solution ...
First view :
#extends('master') #section('title', 'Live Oldham')
#section('content')
#foreach ($business as $businesses)
<a target="_blank" href="{{ url('business/' . $businesses->id) }}"> {{($businesses->name) }}
</a> #endforeach
#endsection
Second Controller :
function displayBusiness($id) {
$business = Business::find($id);
$address = Address::find($id);
return view('displayBusiness', compact('business', 'address'));
}
Second View :
<p>{{$business->name}}</p>
<p>{{$business->email}}</p>
<p>{{$address->firstline_address}}</p>
<p>{{$address->secondline_address}}</p>
<p>{{$address->town}}</p>
<p>{{$address->city}}</p>
<p>{{$address->postcode}}</p>
<p>{{$address->telephone}}</p>
Second Route :
Route::get('business/{id}', 'BusinessController#displayBusiness')->name('displayBusiness');
Route parameters are available in the controller function as parameters. Now you can build a query with this function. If your query does not return any results, you can send the user back to the business overview.
function displayBusiness($name) {
$business = Business::where('name', $name)->orWhere('id', $name)->first();
if ($business === null)
{
// No business with this name or id found.
// Redirect to businesses list page.
}
$address = Address::all();
return view('displayBusiness', ['business' => $business, 'address' => $address]);
}
see docs here about old input
Route::post('/search/all/', function (Request $request) {
//...
$products = $query->paginate(15);
$data = ['products' => $products,
'oldinput' => $request->all()];
return view('inventory.search_products', $data);
});
in the view:
this works:
<input type="text" id="search_all" name="search_all" value="{{ $oldinput['search_all'] }}">
this is always empty:
<input type="text" id="search_all" name="search_all" value="{{ old('search_all') }}">
Just call flush in your controller then you can use old() helper function in your blade.
public function YourController(Request $request){
$request->flash();
return view('yourblade');
}
In blade file:-
<input id="lng" name="lng" value="{{old('lng')}}" type="hidden">
docs says you should flash() then call old() method.
flashing stores the previous request in the session. so it makes sense that old(search_all) doesn't work
I will suggest the following solution:
return view('inventory.search_products', $data)->withInput(\Input::all());
And in blade you can call as well \Input::old('search_all');.