I'm studing Laravel CRUD.
Laravel Framework is 6.18.15
I would like to select of a record and update.
This is photo gallery.
Now if I click one of photo I can get below URL
https://mywebsite.net/public/edit?id=59
but in edit.blade.php I got this error
Undefined variable: id
Could someone teach me correct code please?
These are current code
Controller UPDATED
public function edit(Request $request)
{
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
public function editpcs(Request $request)
{
$this->validate($request, [
'title' => 'required',
'image' => 'required|mimes:jpeg,jpg'
]);
$input['image'] = time().'.'.$request->image->getClientOriginalExtension();
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = time().'.'.$request->image->getClientOriginalExtension();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1280, null, function ($image) {$image->aspectRatio();});
$image_resize->save(public_path('images/ServiceImages/' .$filename));
}
$request->image->move(public_path('images'), $input['image']);
$input['title'] = $request->title;
// ImageGallery::update($input);
$update = DB::table('image_gallery')->where('id', $id)->update( [ 'title' => $request->title, 'image' => $request->image]);
return view('edit',compact('images'))->with('sucess','sucessfully updated');
}
web.php
//edit view
Route::get('edit', 'ImageGalleryController#edit');
Route::post('edit', 'ImageGalleryController#edit');
//edit procces
Route::get('editpcs', 'ImageGalleryController#editpcs');
Route::post('editpcs', 'ImageGalleryController#editpcs');
UPDATE
#if($images->count())
#foreach($images as $image)
<div class='text-center'>
<small class='text-muted'>{{$image['id']}}/ {{$image['title']}} </small>
</div>
#endforeach
#endif
MODEL
namespace App;
use Illuminate\Database\Eloquent\Model;
class ImageGallery extends Model
{
protected $table = 'image_gallery';
protected $fillable = ['title', 'image'];
}
Actually $id is really undefined here, it would be $request->route('id') or request('id') or $_GET['id'] or $request->input('id') :
public function edit(Request $request)
{
$id = request('id');
$images = ImageGallery::findOrFail($id); // use findOrFail() id not exist in table, it throw a 404 error
return view('edit',compact('images'));
}
Take a look at the $_GET and $_REQUEST superglobals. Something like the following would work for your example:
$id = $_GET['id'];
$country = $_GET['country'];
In laravel you can to use Input::get(), But Input::get is deprecated in newer version of laravel, prefer the $request->input instead of Input::get :
$id= $request->input('id');
$country= $request->input('country');
It looks to me like this function:
public function edit(Request $request)
{
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
Should be something like this perhaps?
public function edit(Request $request)
{
$id = $request->input('id', null);
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
As it is, $id appears to be undefined before you attempt to pass it into the find() method. But according to your URL it is in the $request object. So you need to get it from there and into the function. You can read about this method in the docs.
public function edit(Request $request)
{
$id = request('id');
$images = ImageGallery::where('id',$id)->first();
return view('edit',compact('images'));
}
Related
Missing required parameter for [Route: blog.update] [URI: blog/{post}/update] [Missing parameter: post].
in routes :
Route::put('/blog/{post}/update', [BlogController::class, 'update'])->name('blog.update');
in BlogController :
`
public function update(Request $request,Post $post){
$request->validate([
'title' => 'required',
'image' => 'required | image',
'body' => 'required'
]);
$postId = $post->id;
$title = $request->input('title');
$slug = Str::slug($title,'-').'-'.$postId;
// $user_id = Auth::user()->id;
$body = $request->input('body');
//File upload
$imagePath = 'storage/'. $request->file('image')->store('postImages','public');
// $post = new Post();
$post->title = $title;
$post->slug = $slug;
// $post->user_id = $user_id;
$post->body = $body;
$post->imagePath = $imagePath;
$post->save();
return redirect()->back()->with('status', 'Post edited successfully');
dd('validation passed . You can request the input');
}
`
Please solve this issue
I want to update the post
If you are using the route() helper in your form. You can pass the parameter using it :
<form action="{{ route('blog.update', ['post' => $post_id]) }}">...</form>
which is the post is the parameter you name in the route.
Since you haven't posted your blade file so here's the full method:
in your route:
Route::put('/blog/{post}/update' , [BlogController::class, 'update']);
in your blade form make tag like this:
<form method="post" action="/blog/{{$post->id}}/update">
//This will show url like /blog/1/update
//For using PUT method add this:
{{ method_field('PUT') }}
// Do not forget to use #csrf
Then in your controller update function handle the request and $id like this:
public function update(Request $request, $id){
//Find post in your data with help of model
$post = \App\Models\Post::findOrFail($id);
//validate and update with the post instance of Post class
//Feel free to add many functions same as of your controller before i'm leaving empty
$post->update([
//Add fields for update
]);
}
I have Showroompage Controller
public function index()
{
if (request()->category) {
$products = Product::with('categories')->whereHas('categories', function ($query) {
$query->where('slug', request()->category);
})->take(0)->paginate(9);
$categories = Category::all();
} else {
$products = Product::inRandomOrder()->take(0)->paginate(9);
$categories = Category::all();
}
return view('/pages/showroom')->with([
'products' => $products,
'categories' => $categories,
]);
And Route
Route::resource('/showroom', App\Http\Controllers\ShowroomPageController::class);
Route::get('showroom/{product}', 'ShoowroomPageController#show' )->name('show');
My site display wrong title of url
What i can do to display in a url "baran-ogrodzenia.pl/showroom/kategoria=bramy-skrzydlowe" instead of "showroom?category"?
SITE LINK
I have an issue while updating the user. When I try to update the user after clicking the save button then it redirect me to the same page and not throwing me any error but also its not updating anything in the database. Below is my code. I have no idea what's going on here. Help me :)
Controller
public function update(ReportRequest $request, $id)
{
$report = Report::findOrFail($id);
$input = $request->all();
if ($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file' => $name]);
$input['photo_id'] = $photo->id;
}
$report->update($input);
return redirect()->back();
}
Route
Route::resource('admin/reports', 'ReportController', ['names'=>[
'index'=>'admin.reports.index',
'create'=>'admin.reports.create',
'edit'=>'admin.reports.edit',
]]);
Models
class Report extends Model
{
protected $fillable = [
'student_id',
'student_name',
'class_id',
'subject',
'teacher_name',
'report_categories_id',
'total_marks',
'obtained_marks',
'percentage',
'position',
'photo_id',
];
public function photo() {
return $this->belongsTo('App\Photo');
}
public function studentsClass() {
return $this->belongsTo('App\StudentsClass', 'class_id');
}
public function student() {
return $this->belongsToMany('App\Student');
}
}
Make sure you have your $fillable properties in your Photo and Report models, otherwise the create() and update() methods won't work as expected.
Check the $fillable fields in the Model as above. If the error persists check your laravel log on storage/logs/laravel.log.
In controller:
public function update(ReportRequest $request, $id){
$report = Report::findOrFail($id);
$input = $request->all();
try{
if ($request->photo_id != '') {
$path = 'images/';
$file = $request->photo_id;
$name = time() . $file->getClientOriginalName();
$file->move($path, $name);
$photo = Photo::create(['file' => $name]);
$report->update(['photo_id' => $photo->id]);
}
return redirect()->back();
}catch(\Exception $e){
return redirect()->back()->with('error_message', $e->getMessage());
}
}
I use the same view to show one post and random post
routes
Route::get('posts/{id}', 'PostsController#show')->name('posts.show');
Route::get('get-random-post', 'PostsController#getRandomPost');
methods in PostsController
public function show($id) {
$post = Post::findOrFail($id);
return view('posts.show', compact('post'));
}
public function getRandomPost() {
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
return redirect()->route('posts.show', ["id" => $post->id]);
}
but now I need to add a small difference between two views. How can I do that?
UPD
I added variable $randomPost to methods in Controller
public function show($id) {
$randomPost = false;
$post = Post::findOrFail($id);
return view('posts.show', compact('post', 'randomPost'));
}
public function getRandomPost() {
$randomPost = true;
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
return redirect()->route('posts.show', ["id" => $post->id]);
}
and added code below to show view
#if($randomPost)
some text
#endif
but I don't know how to pass variable from getRandomPost() to view?
UPD2
As result I used session, it works but I'm not sure about it
method
public function getRandomPost() {
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
session()->flash('random_post', 'ok');
return redirect()->route('posts.show', ["id" => $post->id]);
}
view
#extends('layouts.app')
#section('content')
Home page
<h2>#{{$post->id}}</h2>
{!! nl2br(e($post->text)) !!}
<?php if(session()->has('random_post')){
echo '<div style="text-align: center">';
echo link_to_action('PostsController#getRandomPost', 'Random Post', $parameters = array(), $attributes = array());
echo '</div>';
}?>
#stop
You can use session flash, it lasts only on subsequent request:
// set
session()->flash('random_post', 'ok');
// check
if(session()->has('random_post')){
// is random
I guess the easiest way would be to call the function from the getRandomPost by passing a default variable through.
public function show($id, $randomPost = false) {
$post = Post::findOrFail($id);
return view('posts.show', compact('post', 'randomPost'));
}
public function getRandomPost() {
$post = Post::inRandomOrder()->where('is_published', 1)->first();
$this->show($post->id, true);
}
I have an update post form, where I need to update the name of the post in posts table and the associated text within the text table. I can't seem to get it to work at all.
Model - Post.php
public function text()
{
return $this->hasOne('Text');
}
Model - Text.php
public function post()
{
return $this->belongsTo('Post');
}
Controller - PostController.php
public function updateQuestionForm($id)
{
$post = Post::find($id);
$input = Input::all();
$rules = array(
'text' => 'required',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::back()->withErrors($validation)->withInput();
} else {
$post->title = Input::get('title');
$post->save();
$text = $post->text();
$text->text = Input::get('text');
$post->text()->save($text);
$message = "Post updated";
return Redirect::to('question/'.$post->id.'/'.$post->slug.'/')->with('message', $message);
}
}