how to hide id in url in laravel? - laravel

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

Related

How to destroy a record using a form in Laravel and display status?

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

how do i pass data value to another page via link in laravel?

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');
}

without select category not show subcategory

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 .

Insert a value to hidden input Laravel Blade

How to pass a value to hidden input ?
Create form :
#if (isset($id))
{!! Form::hidden('edition', $id) !!}
#endif
I got the form id by url like this :
Add Journal
( when I click Add Journal button it will shows a create form with edition id at the url)
and the controller is :
$id = $request->get('edition');
$journal = Edition::findOrFail($id)->journal()->create($input);
The result gave me this error "No query results for model [App\Edition]."
Usually, this is used in Blade templates.
Just pass the name and value to the method.
{{ Form::hidden('invisible', 'secret') }}
This creates a very simple element which looks like the following.
<input name="invisible" type="hidden" value="secret">
To add other attributes, pass a third argument to the method. This third argument must be an array.
{{ Form::hidden('invisible', 'secret', array('id' => 'invisible_id')) }}
Now the input has an id attribute.
<input id="invisible_id" name="invisible" type="hidden" value="secret">
Check out : Creating a Hidden Input Field
If still not work check you project have Laravel Collective installed
In controller method check
public function store(Request $request)
{
$name = $request->input('name');
}
you can do this with the help of blade
<input type="hidden" value="{{$user->id}}" name="user_id">

I want to upload and save image in database but when i try to do it Call to a member function images() on null error shown up

I am beginner in laravel and i want to make image uploading and saving app.
Everything is going cool but as i try to upload images it isnot saved to database.
But in public/gallery/images folder images are present.How this is possible without saving in database.
When i try to upload following error shown up:
FatalErrorException in GalleryController.php line 71:
Call to a member function images() on null
My controller is:
public function doImageUpload(Request $request){
//get the file from the post request
$file = $request->file('file');
//set my file name
$filename = uniqid() . $file->getClientOriginalName();
//move the file to correct location
$file->move('gallery/images',$filename);
//save image details into the database
$gallery = Gallery::find($request->input('gallery_id'));//get the gallery_id
$image = $gallery->images()->create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
My view is:
<div class="row">
<div class="col-md-12">
<form action="{{url('image/do-upload')}}"
method="POST" enctype="multipart/form-data">
<label>Select image to upload:</label >
<input type="file" name="file" id="file">
<input type="submit" value="Upload" name="submit">
<input type="hidden" name="_token" value={{ csrf_token() }}>
</form>
</div>
and my image model is:
class Image extends Model
{
protected $fillable = [
'gallery_id','file_name','file_size','file_mime','file-path','created_by'
];
public function gallery(){
return $this->belongsTo('App\Gallery');
}
}
Being new to laravel i didnt get the actual error meaning Call to a member function images() on null??
How to fix this?
do a log debug on $gallery after you use the find method, there's a good chance it's not initialized, if the find method fails to find the id you've given it, it returns null
a good practice would be to verify you get an object back and verify your input contains gallery_id and that it is a number > 0
if ($request->has('gallery_id') && intval($request->input('gallery_id'))>0){
$gallery = Gallery::find($request->input('gallery_id'));//get the gallery_id
if ($gallery){
$image = $gallery->images()->create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
} else {
return Response::make('no gallery found with this $request->input('gallery_id') gallery_id',404);
}
} else {
return Response::make('invalid gallery_id as input',400);
}
you could also create the image via the Image create method as is instead of using the gallery relationship, that would have created an image probably with the gallery_id of 0 if the galley_id input is incorrect.
$image = Image::create([
'gallery_id'=>$request->input('gallery_id'),
'file_name'=>$filename,
'file_size'=>$file->getClientSize(),
'file_mime'=>$file->getClientMimeType(),
'file_path'=>'gallery/images/' . $filename,
'created_by'=>1,
]);
I don't know if you resolved the problem, but I had the same issue and I found the solution.
When you send a form, you need to put a hidden input .
<input type"hidden" name="gallery_id" value="{{ $gallery->id }}">
I'm sure you work on the same project as me, DropZone Gallery, if so I think you have the solution

Resources