How to Fix Undefined Variable id error in laravel 5.7 - php

M working on a solution where by i need to pass data from controller to view, Based on the id.
I've tested each variable one by one for see if there is actual data contained in those variables.
one-by-one produces all the values required and as soon as i comment out the var_dumps(). Throws an Undefined index error.
Please See code below:
View
<td>
<a href="view-campaign/{{$item->id}}" class="btn btn-success mb-2"
data-toggle="tooltip" title="view campaign">
<i class="fa fa-eye"></i>
</a>
</td>
Controller
public function viewCampaign($id){
//return var_dump($id);
$img = null;
//firebase configs and send to firebase
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/serviceKey.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->withDatabaseUri('https://projectName.firebaseio.com/')
->create();
$database = $firebase->getDatabase();
$ref = $database->getReference('CampaignCollection')->getValue();
foreach($ref as $key){
$item = $key['id'];
//return var_dump($item);
$poster = $key['Poster'];
//return var_dump($poster);
if($item = $id){
//return '1';
$img = $poster;
//return var_dump($poster);
}else{
return '0';
}
}
return view('view-campaign')->with('img',$img);
}
Route
Route::get('view-campaign/{id}','CampaignController#viewCampaign');
View::Results
#extends('layouts.layout')
#section('content')
<div class="col-md-12">
<div class="col-md-12 panel">
<div class="col-md-12 panel-heading">
<h4>View Campaign:</h4>
</div>
<div id="imgContainer" class="col-md-12 panel-body">
<i class="fa fa-arrow-circle-left"></i>
#if(isset($img))
<div align="center">
<img src="{{($img)}}" />
</div>
#else
no data
#endif
</div>
</div>
</div>
#endsection
Goal is to get the base64 code to pass to the view.

Try replacing your foreach with the following code:
foreach($ref as $k1 => $key){
$item = $key->id; //change over here
//return var_dump($item);
$poster = $key->Poster; //change over here
//return var_dump($poster);
if($item == $id){ //change over here
//return '1';
$img = $poster;
//return var_dump($poster);
}else{
return '0';
}
}
I reckon, you would also have to update the function signature to look something like following:
public function viewCampaign(Request $request , $id){
//your code
}

Related

Undefined variable $p and foreach() argument must be of type array|object, null given in codeigniter 3

I am trying to pass an array that gets initialised when it gets queried from the database.
The array of products that I try to pass and display in the view just throws an error and i cannot figure out why.
I am using codeigniter 3.
ProductsModel.php
function get_all_products()
{
$this->db->select("produceCode,description,category,supplier, quantityInStock, bulkSalePrice,photo");
$this->db->from('products');
$query = $this->db->get();
return $query->result();
}
ProductsController.php
public function listProducts()
{
$data['p']=$this->ProductsModel->get_all_products(/*2, $this->uri->segment(3)*/);
$this->load->view('products',$data);
}
products.php
<?php foreach( $p as $row) { ?> // line of code thats causing the error
<div class="col-md-3">
<div class="card p-3">
<div class="text-center"> <!--<img src="../assets/images/products/thumbs/--><?php /*$row->photo;*/?>" width="200"> </div>
<div class="product-details"> <span class="font-weight-bold d-block">$ 7.00</span> <span><?php echo 'hi'/*$row->description;*/?></span>
<div class="buttons d-flex flex-row">
<div class="cart"><i class="fa fa-shopping-cart"></i></div> <button class="btn btn-success cart-button btn-block"><span class="dot">1</span>Add to cart </button>
</div>
</div>
</div>
</div>
<?php } ?>
any suggestions would be great
You are returning a variable named $data in your controller, but in your view you are looping through $p.
Try this:
foreach ($data['p'] as $row)

Laravel 7 Delete array or single image from db and disk - Deletes post but not associated images from db nor disk

In Laravel 7, I am have a task management app. I can upload tasks (posts if it were a blog) and images. I have a multiple image upload working as expected. When it comes time to delete a task, the task deletes just fine but the images are left in the database and in the disk which is public into a folder called task-images. Being new to Laravel, I am struggling on how to go about this. I tried to change the settings in the filesystem.php (which I will post with the commented out code) but that didn't change the location as I had expected. In the end, I want to be able to delete the multiple images when I delete a post and also click delete on an individual image and delete that from both db and disk. I am using resource controller for all my task routes. I have no idea how to go about this and the tutorials that I have found don't really address my specific issue. Any help would be greatly appreciated. Thank you in advance.
Here is my task controller at TaskController.php
<?php
namespace App\Http\Controllers;
use App\Task;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class TasksController extends Controller
{
public function index()
{
$tasks = Task::orderBy('created_at', 'desc')->paginate(10);
return view('/tasks')->with('tasks', $tasks);
}
public function create()
{
return view('tasks.create');
}
public function store(Request $request)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
// Create Task
$user = Auth::user();
$task = new Task();
$data = $request->all();
$task->user_id = $user->id;
$task = $user->task()->create($data);
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
$images = new Image;
$images->name = $name;
}
}
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->task_status;
$task->save();
return redirect('/home')->with('success', 'Task Created');
}
public function edit($id)
{
$task = Task::find($id);
return view('tasks.edit', ['task' => $task]);
}
public function update(Request $request, $id)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
$task = Task::find($id);
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->input('task_status');
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
}
}
$task->update();
return redirect('/home')->with('success', 'Task Updated');
}
public function show($id)
{
$task = Task::find($id);
return view('tasks.show')->with('task', $task);
}
public function destroy($id)
{
$task = Task::findOrFail($id);
// $image = '/task-images/' . $task->image;
Storage::delete($task->image);
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
}
filesystem.php (just the disks section)
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
// 'root' => public_path('task-images'),
],
...
in my individual show template, show.blade.php complete in case there is a code conflict.
#extends('layouts.master')
#section('content')
<div class="container">
Go Back
<div class="card p-3">
<div class="row">
<div class="col-md-4 col-sm-12">
<h3>Task</h3>
<p>{{ $task->task_name }}</p>
<h3>Assigned On:</h3>
<p>{{ $task->created_at->format('m/d/Y') }}</p>
<h3>Assigned To:</h3>
<p>{{ $task->task_assigned_to }}</p>
</div>
<div class="col-md-4 col-sm-12">
<h3>Task Description</h3>
<p>{{ $task->task_description }}</p>
<h3>Priority</h3>
<p>{{ $task->task_priority }}</p>
<h3>Status</h3>
<p>{{ $task->task_status }}</p>
</div>
<div class="col-md-4 col-sm-12">
<h3>Test Environment Date:</h3>
<p>{{ $task->task_to_be_completed_date }}</p>
<h3>Notes</h3>
<p>{{ $task->task_notes }}</p>
<h3>Action</h3>
<div style="display: inline;">
<a href="/tasks/{{$task->id}}/edit" class="btn btn-sm btn-primary mr-2">
<i class="fa fa-edit"></i> Edit
</a>
</div>
<form style="display: inline;" action="/tasks/{{ $task->id }}" method="POST" class="">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm ml-1 mr-1">
<i class="fa fa-trash"></i> Delete
</button>
</form>
</div>
<div class="col-md-12">
<h5>Images</h5>
<hr />
<div class="row">
#if($task->image->count()>0)
#for($i=0; $i < count($images = $task->image()->get()); $i++)
<div class="col-lg-4 col-md-6 col-sm-12">
<img class="w-50 mb-2" src="/task-images/{{ $images[$i]['name'] }}" alt="">
<form style="display: inline;" action="/tasks/{{ $task->name }}" method="POST" class="">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm ml-1 mr-1">
<i class="fa fa-trash"></i> Delete
</button>
</form>
</div>
#endfor
#else
<p>No images found</p>
#endif
</div>
<br />
</div>
</div>
</div>
</div>
<!--Modal Start-->
<div id="lightbox" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog">
<button type="button" class="close hidden" data-dismiss="modal" aria-hidden="true">×</button>
<div class="modal-content">
<div class="modal-body">
<img class="w-100" src="" alt="" />
</div>
</div>
</div>
</div>
<!--Modal End-->
#endsection
#section('scripts')
<script>
$(document).ready(function() {
var $lightbox = $('#lightbox');
$('[data-target="#lightbox"]').on('click', function(event) {
var $img = $(this).find('img'),
src = $img.attr('src'),
alt = $img.attr('alt'),
css = {
'maxWidth': $(window).width() - 100,
'maxHeight': $(window).height() - 100
};
$lightbox.find('.close').addClass('hidden');
$lightbox.find('img').attr('src', src);
$lightbox.find('img').attr('alt', alt);
$lightbox.find('img').css(css);
});
$lightbox.on('shown.bs.modal', function (e) {
var $img = $lightbox.find('img');
$lightbox.find('.modal-dialog').css({'width': $img.width()});
$lightbox.find('.close').removeClass('hidden');
});
});
</script>
#endsection
In my Task model, Task.php, I have:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Image;
class Task extends Model
{
protected $fillable = [
'task_name', 'task_priority', 'task_assigned_to', 'task_assigned_by', 'task_description', 'task_to_be_completed_date', 'task_status',
'task_notes'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function image()
{
// return $this->hasMany('App\Image');
return $this->hasMany(Image::class);
}
}
and finally my Image Model Image.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Task;
class Image extends Model
{
protected $fillable = [
'task_id',
'name',
];
protected $uploads = '/task-images/';
public function getFileAttribute($image)
{
return $this->uploads . $image;
}
public function task()
{
// return $this->belongsTo('App\Task', 'task_id');
return $this->belongsTo(Task::class);
}
}
If I am missing something, please let me know so I can edit my question. Again, thank you in advance for helping me with this issue. I have been scratching my head all week on this one. Cheers.
Edit
After implementing boot functions in my model as suggested below, I received an error that an invalid argument was used for foreach. I ran a dd($task); and the following image shows the result.
Final Edit
The answer below worked for my situation. I did have to edit some things to finalize the resolution:
in Task.php I changed the foreach to the following.
foreach($task->image ?: [] as $image)
I had declared image and not image in my model and that was causing a problem. Adding the ternary operator also helped the code not throw any errors.
In my TasksController.php I changed both the update and create functions with the same ternary operator as follows:
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files ?: [] as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
}
}
I hope this helps anyone else having the same issue. Thanks to #GrumpyCrouton and #lagbox for their help in resolving this as well as #user3563950
Without them, I would still by stratching my head for another couple of weeks.
on your App\Image class, implement to boot function with the following;
use Illuminate\Support\Facades\Storage;
public static function boot() {
parent::boot();
self::deleting(function($image) {
Storage::delete(Storage::path($image->name));
});
}
Also implement the boot method in App\Task class
use Illuminate\Support\Facades\Storage;
public static function boot() {
parent::boot();
self::deleting(function($task) {
foreach($task->images as $image) {
$image->delete();
}
});
}
Now on your TaskController implement the destroy method as follows;
public function destroy($id)
{
$task = Task::findOrFail($id);
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
As a bonus, learn Laravel model binding to ease the pain of finding an instance using findOrFail()

PHP routing: The GET method is not supported for this route. Supported methods: POST

I have an HTML form defined as follows:
<form action="{{route('save.checkout')}}" method="POST">
{{csrf_field()}}
<input name="amount" type="hidden" value="{{session()->get('cart')->totalprice}}">
<div class="cart_navigation">
<a class="continue-btn" href="#">
<i class="fa fa-arrow-left"> </i> خرید را ادامه دهید
</a>
<a class="checkout-btn" href="{{route('save.checkout')}}">
<i class="fa fa-check"></i> ادامه به پرداخت
</a>
</div>
</form>
The following error is being thrown when submitting the form:
The GET method is not supported for this route. Supported methods: POST.
my route is:
route::post('/savecheckout','BasketController#checkout')->name('save.checkout');
and the checkout function:
public function checkout(Request $request){
$user = auth()->user()->id;
$order = new order();
$order->user_id = $user;
$order->amount = $request->input('amount');
$order->status = 0;
$order->save();
$order = order::where('status' ,0)->where('user_id', $user)->first();
return view('checkout.index', compact('order'));
}
i solved the problem . it was a silly mistake i changed my button type to submit
if you are beginning with Laravel so i would like to contribute something to make your programming better & safer for future projects.
always validate your input
use of try & catch blocks
show appropriate error message to your users so that you can also
debug it in future.
so the modified code will be look like:
public function checkout(Request $request){
// use Validator; (add this after namespace to import validator)
$validator = Validator::make($request->all(),[
'user_id' => 'required|integer|max:11',
'amount' => 'required|numeric',
'status' => 'sometimes|integer|max:1',
]);
if($validator->fails()) {
return back()->withErrors($validator);
}
try {
$user = auth()->user()->id;
$order = new order();
$order->user_id = $user;
$order->amount = $request->input('amount');
$order->status = 0;
$order->save();
$request->session()->flash('message', 'Order Successfully Created');
$order = order::where('status' ,0)->where('user_id', $user)->first();
return view('checkout.index', compact('order'));
} catch (\Exception $e){
dd($e->getMessage()); // it will show the error message with, you can replace this block with redirect code or anything else..
}
}
for showing error & success message in front-end use below code in your checkout > index.blade.php template (just a sample code, you can make it more better by using your own CSS & styles)
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
#if(count($errors) > 0)
<div class="note note-error">
<h4>Error..!!</h4>
<p>
#foreach($errors->all() as $error)
<div class="alert alert-danger fade in m-b-15">
<i class="fa fa-chevron-right"></i>
{{ $error }}
<span class="close" data-dismiss="alert">×</span></div>
#endforeach
</p>
</div>
#endif

How to update and delete comments from database?

First of all, I want to save comments after editing.I'm able to save the other features, but now I need to save comments too because they are in other table.
Here is my code for comments:
#foreach($event_comm as $comm)
<div class="row">
<div class="col-md-4">
<label class="label" style="color: black">Comment by {{$comm->user->username}}</label>
<label class="input">
{{ Form::text('comments', $comm->comments) }}
</label>
#endforeach
My update function
public function update($type, $id)
{
/* print_r(Input::all()); die; */
if($type == "Opinion")
{
$article = \App\Opinion::find($id);
$article->subject = Request::input('subject');
$article->public = Request::input('public');
$article->category_id = Request::input('category_id');
$article->opinion = Request::input('opinion');
$article->update();
}
if($type == "Event")
{
$event_comm = EventComment::where('event_id', $id)->get();
$article = \App\Event::find($id);
$article->subject = Request::input('subject');
$event_comm->comments = Request::input('comments');
$article->public = Request::input('public');
$article->category_id = Request::input('category_id');
$article->website = Request::input('website');
$article->email = Request::input('email');
$article->telephone = Request::input('telephone');
$article->information = Request::input('information');
$article->update();
}
return redirect(URL::previous())
->with(compact('event_comm'));
}
I've already tried to add $event_comm->comments = Request::input('comments'); but doesn't work.
2.Second problem.I want to also delete comments from database with a button or something like that.I found a route but I'm not sure if works.I need to know how to add this into my file?With a button ?
My route
Route::get('admin/article/deleteComment/{type}/{id}',['as' => 'deleteComment', 'uses' => 'ArticleController#deleteComment']);
public function deleteComment($type, $id)
{
if($type == "Event")
{
$comment = \App\EventComment::find($id);
}
if($type == "Opinion")
{
$comment = \App\OpinionComment::find($id);
}
$comment->delete();
return redirect('admin/comments');
}
Button:
<button href="{{ url('deleteComment',$type, $id) }}" role="button" class="btn btn-xs btn-danger" onclick="return confirm('Are you sure you want to delete this comment?');">Delete <i class="fa fa-trash"></i></button>

On clicking a link, url changes but not redirected to the required page in laravel 5.2 blade

I have a list page where there are images. On clicking each image, the page should go to its corresponding detail page. So I have an a href attribut where I defined route by passing its id.
Below is my blade
#foreach (array_chunk($program, 3, true) as $prgms)
<div class="card-deck mb-30">
#foreach ($prgms as $prgm)
<div class="col-md-4 card">
<a href="{{url('programDtls/'.$prgm['id'])}}">
<img class="card-img-top" src="{{asset(App\Http\Controllers\Controller::getThumbPath($prgm['thumbnail'],$folder='home'))}}" alt="Card image cap">
<div class="card-body">
<h4 class="card-title">{{$prgm['title']}}</h4>
<p class="card-text clsComInnerText mb-10">{{$prgm['description']}}</p>
<p class="card-text"><small class="text-muted">{{date('d-m-Y',strtotime($prgm['episode_date']))}} {{$prg_time}} {{$day = date('l', strtotime($prgm['episode_date']))}} </small></p>
</div>
</a>
</div>
#endforeach
</div>
#endforeach
List page Route
Route::get('programListPage/{id}', 'ProgramListPageController#index');
Detail page Route
Route::get('programDtls/{id}', 'ProgramDtlsController#index');
ProgramListPageController#index
public function index($id) {
$category_details = Category::select('title','description')->where('id',$id)->first();
$program = ProgramDetails::select('id','title','description','thumbnail','programs_id','episode_date')->where('category_id',$id)->where('category_videos',1)->where('enabled',1)->get()->toArray();
$trending_video = ProgramDetails::select('video_url','thumbnail')->where('is_trending',1)->where('category_id',$id)->first();
if(count($trending_video)>0){
$trending = $trending_video['video_url'];
$image = $trending_video['thumbnail'];
}else{
$trending = " ";
$image = " ";
}
if(count($program)>0){
foreach ($program as $prgm) {
$prg_times = Programslots::where('programs_id',$prgm['programs_id'])->get();
foreach($prg_times as $time){
$prg_time = date('h:ia ', strtotime($time['show_time']));
}
}
}else{
$prg_time = " ";
$day = " ";
}
return View('programListPage', ['category_details' => $category_details, 'program' => $program,'prg_time' => $prg_time,'trending_video'=>$trending,'image'=>$image]);
}
ProgramDtlsController#index
public function index($program_details_id) {
$program_id = ProgramDetails::select('programs_id','description','title','episode_no','video_url','thumbnail')->where('id',$program_details_id)->get();
$program = Programs::select('id','poster_image','video_url','is_video','description')->where('id',$program_id[0]['programs_id'])->orderBy('updated_at', 'desc')->get();
$video_url=ProgramDetails::select('id','video_url','thumbnail','title','episode_no','description','promo_url')->where('enabled', 1)->where('programs_id',$program[0]['id'])->get()->toArray();
$featured_image= Programs::select('poster_image')->where('is_featured', 1)->orderBy('updated_at', 'desc')->get();
$image_album= AlbumMaster::select('id','album_title','cover_image')->where('enabled', 1)->where('program_details_id',$program_details_id)->orderBy('updated_at', 'desc')->get();
$image_gallery=PhotoGallery::select()->where('album_master_id',$image_album[0]['id'])->get();
$result = array('program_id'=>$program_id,'program' => $program,'video_url'=>$video_url,'featured_image'=>$featured_image,'image'=>$image_gallery,'image_album'=>$image_album);
return View('programDtls')->with($result);
}
Here what happens is, when I click an image the url changes like the below
http://localhost/abcde/public/programDtls/31
But displays the same list page itself. But if I again refreshes with the details page url, it moves to the corresponding detail page.What I need is to go to the detail page on clicking the images in the listing page. Thanks in advance,

Categories