How to get data from Database to view page in laravel 7 - php

I wont to fetch data from database and show them in a view page as a table. I tried so many ways and didn't work. Also I have used member adding form as a model in my home.blade.php and it works fine.
here is my home.blade.php
<!-- show tasks -->
<div class="container-fluid">
<div class="container mt-4">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Task</th>
<th scope="col">Assigned Date</th>
<th socpe="col">Sign-off Date</th>
<th socpe="col">Edit/Delete</th>
</tr>
</thead>
#foreach($tasks as $task)
<tr>
<td>{{$task->id}}</td>
<td>{{$task->task}}</td>
<td>{{$task->assigned_date}}</td>
<td>{{$task->end_date}}</td>
<td>
Delete
Edite
</td>
</tr>
#endforeach
</table>
</div>
</div>
<!-- end Show tasks -->
here is my taskController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\task;
class taskController extends Controller
{
public function store(Request $request){
$this->validate($request,[
'task'=>['required', 'max:100', 'min:5'],
'assignedDate' => ['required', 'date'],
'endDate' => ['required', 'date'],
]);
$task = new task;
$task->task = $request->task;
$task->assigned_date = $request->assignedDate;
$task->end_date = $request->endDate;
$task->save();
return redirect()->back()->with('message', 'Task added successfuly');
}
public function getdata()
{
$data=task::all();
return view('home')->with('tasks', $data);
}
}
and here is my web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::post('/saveTask', 'taskcontroller#store');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
So, What am I doing wrong here? Can somebody please explain me?

Change your Last Route to
Route::get('/home', 'HomeController#getdata')->name('home');

Related

Routing Error Due to a group prefix in my route

In my routing if i remove the {page} prefix it works completely fine but when i put it i get an error. For other it is working fine but it is not working for this route: Route::get('/{categories}', 'AdminVisible\CostIncludeController#index');
My AdminPageController:
public function index($page)
{
$page = Page::where('Pages_Slug_Name',$page)->firstorFail();
$pages = Page::all();
return view('admin.pages.page',[
'page' => $page,
],compact('pages'));
}
My CostIncludeController:
public function index($categories){
$pages = Page::all();
$packages = Package::where('slug',$categories)->first();
return view('admin.pages.costinclude',[
'packages' => $packages,
],compact('pages'));
}
My Route:
Auth::routes(['register' => false,'login' => false]);
Route::prefix('admin')->group(function() {
Route::get('/')->name('login')->uses('Auth\LoginController#showLoginForm');
Route::post('/')->name('login')->uses('Auth\LoginController#login');
Route::get('/dashboard', 'AdminVisible\HomeController#index')->name('admin.dashboard');
Route::prefix('pages')->group(function() {
Route::get('/','AdminVisible\AdminPageController#pages')->name('pages');
Route::prefix('{page}')->group(function() {
Route::get('/','AdminVisible\AdminPageController#index')->name('page');
Route::get('/banner', 'AdminVisible\BannerController#index');
Route::get('/why-with-us', 'AdminVisible\WhyWithUsController#index');
Route::get('/testimonials', 'AdminVisible\TestimonialsController#index');
Route::get('/about', 'AdminVisible\AboutController#index');
Route::get('/about-why-with-us', 'AdminVisible\AboutWhyWithUsController#index');
Route::get('/general-information', 'AdminVisible\PackageController#index');
Route::get('/package-program', 'AdminVisible\PackageController#index');
Route::get('/cost-exclude', 'AdminVisible\PackageController#index');
Route::prefix('cost-include')->group(function() {
Route::get('/', 'AdminVisible\PackageController#index');
Route::get('/{categories}', 'AdminVisible\CostIncludeController#index');
});
});
});
});
My blade.php file:
#extends('layouts.app')
#section('style')
<link href="{{ asset('css/Admin/sql-data-viewer.css') }}" rel="stylesheet">
<style></style>
#endsection
#section('content')
<section class="data-viewer">
<div class="d-flex justify-content-between">
<h3>Select Package to change</h3>
<button type="button" class="btn add-data text-white rounded-pill">Add <i class="fas fa-plus"></i></button>
</div>
<table>
<thead>
<tr class="data-head">
<td scope="col" style="width: 5%"><input type="checkbox"></td>
<th scope="col" style="width: 8.7%">Id</th>
<td scope="col">Includes</td>
</tr>
</thead>
<tbody>
#foreach ($packages->costIncludes as $include)
<tr class="data">
<td scope="col" style="width: 6.5%"><input type="checkbox"></td>
<th scope="col" style="width: 10%;">{{$include->id}}</th>
<td scope="col" class="text-justify" style="width:696px">{{Str::limit($include->Cost_Include,100)}}</td>
</tr>
#endforeach
</tbody>
</table>
</section>
#endsection
With {page} prefix:
Without {page} prefix:
With {page} prefix when i do dd():
Without {page} prefix when i do dd():
In your CostIncludeController#index, add the new variable. The router is expecting you to handle two variables.
public function index($page, $categories){
$pages = Page::all();
$packages = Package::where('slug',$categories)->first();
return view('admin.pages.costinclude',[
'packages' => $packages,
],compact('pages'));
}
You can confirm the cause of the error by doing a dd($categories) inside your controller function in both cases.
It seems we need to pass $page parameter in the CostIncludesController. This same question is answered in this post:
I am having trouble with my route in laravel

no error, but data not shown, stuck in processing

enter image description here
These are my files which is not showing my data in html only data is processing and no error also. I want to look my database through laravel in a html file but it's only processing and also not showing any error. so please help me on this error.
no error, the ajax response is good, but data not shown and processing box keeps showing.
Yajra 9.0
Laravel 5.8
MemberController.php
<?php
namespace App\Http\Controllers;
use App\Models\Member;
use Illuminate\Http\Request;
use Datatables;
use Validator;
class MemberController extends Controller
{
public function addSocialMember(){
return view("home.views.social-member");
}
public function listMember(){
return view("home.views.memberlist");
}
public function listAllMember(){
$memberlist = Member::query();
return Datatables::of($memberlist)->make(true);
}
public function saveMember(Request $request){
$validator = Validator::make(array(
"name"=>$request->name,
"email"=>$request->email,
"phone"=>$request->phone,
"state"=>$request->state,
"city"=>$request->city,
"issue"=>$request->issue,
"message"=>$request->message,
),array(
"name"=>"required",
"email"=>"required|unique:member",
"phone"=>"required",
"state"=>"required",
"city"=>"required",
"issue"=>"required",
"message"=>"required",
));
if($validator->fails()){
return redirect("social-member")->withErrors($validator)->withInput();
}else{
//successfully we have passed our form
$member = new Member;
$member->name = $request->name;
$member->email = $request->email;
$member->phone = $request->phone;
$member->state = $request->state;
$member->city = $request->city;
$member->issue = $request->issue;
$member->message = $request->message;
$member->save();
$request->session()->flash("message","Member has been submitted form successfully");
return redirect("social-member");
}
}
}
Memberlist.blade.php
#extends("home.layouts.layout")
#section("title","Social Member | Bheekho Foundation")
#section("content")
<div class="container padding-top-three">
<br/>
<blockquote><h4>We need Help</h4></blockquote>
<br/>
<div class="row">
<div class="col-md-12">
<table class="table table-striped table-bordered" id="memberlist">
<thead>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>State</th>
<th>City</th>
<th>Issue</th>
<th>Describe Your Issues</th>
<th>Status</th>
</thead>
</table>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3./jquery.min.js"></script>
#endsection
web.php
<?php
Route::get("/","HomeController#homepage");
//Social Member Route
Route::get("/social-member","MemberController#addSocialMember")->name("addsocialmember");
Route::get("/memberlist","MemberController#listMember")->name("listmember");
Route::get("/memberlist-data","MemberController#listAllMember")->name("listallmember");
Route::post("/save-member","MemberController#saveMember")->name("savemember");

htmlspecialchars() expects parameter 1 to be string, object given

This is Controller. I named it CartController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Gloudemans\Shoppingcart\Facades\Cart;
use App\Product;
class CartController extends Controller
{
public function index()
{
$cartItems=Cart::content();
return view('cart.index', compact('cartItems'));
}
public function edit($id)
{
$product=Product::find($id);
Cart::add($id,$product->name,'1',$product->price);
}
This is my welcome.blade.php. This is the page where I display all my Items.
<div class="row">
#forelse($books->chunk(4) as $chunk)
#foreach($chunk as $book)
<div class="column-prod">
<a href="{{url('view')}}">
<div class="card-prod">
<center><img src="{{url('images',$book->image)}}" style="width: 300px; height: 300px;"></center> </a>
<div class="container-prod">
<h2></h2>
<p class="title">{{$book->name}}</p>
<p class="price">₱ {{$book->price}}</p>
<p><i class="fas fa-cart-arrow-down"></i>Add to Cart</button></p>
<p><button class="button"><i class="fas fa-heart"></i> Add to Wishlist</button></p>
</div>
</div>
</div>
#endforeach
#empty
<h3> No Books </h3>
#endforelse
</div> <!--Div all end-->
This is the codes of my Cart Page. When the user click add to cart in the welcome page, his/her chosen items will be place in this page.
<h3> Cart Items </h3>
<!--TABLE NAMESSS-->
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Image</th>
<th scope="col">Name</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
#foreach($cartItems as $cartItem)
<li>{{$cartItem->name}}</li>
<tr>
<td>{{url('images',$cartItem->image)}}</td>
<td>{{$cartItem->name}}</td>
<td>{{$cartItem->price}}</td>
<td>{{$cartItem->qty}}</td>
</tr>
#endforeach
</tbody>
</table>
This is my route.
Route::get('/', function () {
return view('welcome')->with(['books' => \App\Product::all()]);
});
Route::get('/cart','ShopController#cart');
Route::get('/signin','ShopController#signin');
Route::resource('/cart','CartController');
Route::get('/wishlist','ShopController#wish');
Auth::routes();
Route::get('/logout', 'Auth\LoginController#logout');
Route::get('/home', 'HomeController#index');
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function(){
Route::get('/',function(){
return view('admin.index');
})->name('admin.index');
Route::resource('product','ProductsController');
Route::resource('category','CategoriesController');
});
Route::get('/categ', function(){
return view ('admin.category.categ_index');
});
I'm confused I don't know how to fix my error. This is the complete error that the system return.
"htmlspecialchars() expects parameter 1 to be string, object given (View: C:\xampp\htdocs\Shop\resources\views\welcome.blade.php)"
I hope you can help me in solving this. Your answers are very much appreciated.

Laravel: one-to-many retrieving single record in view

I'm currently learning Laravel 5.6. So my problem is this, I have the following Model:
class Tour extends Model
{
//
protected $fillable = [
'name',
'price',
'category',
'overview',
'activity',
'exclusion',
'inclusion',
'policies',
'guide_id',
'province_id'
];
public function tourImages(){
return $this -> hasMany('App\TourImage');
}
}
class TourImage extends Model
{
//
protected $fillable = [
'name',
'path',
'tour_id'
];
public function tour(){
return $this -> belongsTo('App\Tour');
}
}
So 1 Tour can have multiple TourImages. What i want to do is that i want to print out all the tours on the index page. But i only want to take one TourImage file to display for each tour. I return only array of all tours from controller. Is there a way that i can retrieve image directly on the blade view without returning more variable from the controller?
Here's what I write for my index method:
public function index($province_id = null)
{
$tours = Tour::where('province_id', $province_id)->get();
return view('tours.index', ['tours' => $tours]);
}
Here's my index view:
#extends('layouts.app')
#section('content')
<div class="col-md-8 offset-md-2">
<br/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Picture</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
#foreach($tours as $tour)
<tr>
<th scope="row">{{ $tour->id }}</th>
<td>{{ $tour->name }}</td>
<td><img src="/storage/{{ $tour->tourImages->path }}" width="200px"/></td>
<td>{{ $tour->price }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
you can pass one image of each tour by this code :
$tours=Tour::with(['tourImages'=>function($query){
$query->first();
}])->get();
and in view:
#foreach($tours as $tour)
#if ($tour->tourImages->count())
<img src="/storage/{{ $tour->tourImages[0]->path }}" width="200px"/>
#endif
#endforeach
you need to use with() to get records.like this.
$tours = Tour::with('tourImages')->where('province_id', $province_id)->get();
You can add new relation in your Tour model like
public function latestTourImage() {
return $this->hasOne('App\TourImage')->latest();
}
Then you can fetch it using this in your controller file
$tours = Tour::with('latestTourImage')->where('province_id', $province_id)->get();
and then you can print it in your blade file like
$tour->latestTourImage->path

Laravel 5.2 delete function gave me NotFoundHttpException

I'm using Laravel 5.2 and trying to do an add and delete a data that I already Inputted but when i clicked "Delete" button it gave me NotFoundHttpException.
Here's example of my delete function code in controller:
<?php
namespace App\Http\Controllers\Track;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
//use Illuminate\Support\Facades\Input;
use Validator;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Track as Track;
class TrackController extends Controller
{
/*Display track registry*/
public function index()
{
$data = array('track' => Track::all());
return view('admin.dashboard.tracks.track',$data);
}
/*Display create track form*/
public function create()
{
return view('admin.dashboard.tracks.createtrack');
}
/*Save data form*/
public function saveTrack(Request $request)
{
$input = $request->all();
$messages = array(
'trackCode.required'=>'Track code required.',
'trackCode.unique'=>'Track code already exist.',
'trackName.required'=>'Track name required.',
);
$rule = array(
'trackCode' => 'required|unique:track',
'trackName' => 'required|max:60',
);
$validator = Validator::make($input, $rule, $messages);
if($validator->fails()) {
#Directed to the same page with error message
return Redirect::back()->withErrors($validator)->withInput();
#Validate Success
}
$track = new Track;
$track->trackCode = $request['trackCode'];
$track->trackName = $request['trackName'];
if (! $track->save())
App::abort(500);
return Redirect::action('Track\TrackController#index')->with('successMessage','Track data "'.$input['trackName'].'" has been inserted.');
}
/*Delete data*/
public function delete($id)
{
echo $id;
/*$trackCode = Track::where('trackCode','=',$id)->first();
if($trackCode==null)
App::abort(404);
$trackCode->delete();
return Redirect::action('track');*/
}
}
and here's the part of my delete option code:
<div class="box-body">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 150px; text-align: center;">Track Code</th>
<th>Track Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($track as $itemTrack)
<tr id="track-list" name="track-list">
<td style="text-align: center;">{{ $itemTrack->trackCode }}</td>
<td>{{ $itemTrack->trackName }}</td>
<td><a href="{{{ action('Track\TrackController#delete',[$itemTrack->trackCode]) }}}" title="Delete" onclick="return confirm('Are you sure you want to delete this track : {{{$itemTrack->trackCode.' - '.$itemTrack->trackName }}}?')">
<span class="label label-danger"><i class="fa fa-trash"> Delete </i></span>
</a>
</td>
</tr>
#endforeach
</tbody>
</table>
<br/>
<button class="btn btn-success pull-right" type="submit">Add Data</button>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
whenever it appears the data and i try to delete it, it went to a page and there's NotFoundHttpException error instead of showing me the $id of the data.
Can someone help and explain? thanks
-Edited part-
Routes:
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => 'web'], function()
{
Route::auth();
});
//Route as admin
Route::group(['middleware' => ['web','role:admin']], function()
{
Route::get('/users/dashboard', 'UserController#index');
/*-----------------------------------------------Track Part---------------------------------------------------------*/
/*Track index*/
Route::get('/users/programs/track', array('as'=>'track', 'uses'=>'Track\TrackController#index'));
/*Create track form*/
Route::get('/users/programs/track/create', array('as'=>'track.create', 'uses'=>'Track\TrackController#create'));
/*Route to save track*/
Route::post('/users/programs/track/save', array('as'=>'track.save', 'uses'=>'Track\TrackController#saveTrack'));
/*Delete track*/
Route::get('/users/programs/track/{$id}/delete', array('as'=>'track.delete', 'uses'=>'Track\TrackController#delete'));
/*-----------------------------------------------Course Part---------------------------------------------------------*/
//Display course menu
Route::get('/users/programs/course', array('as'=>'course', 'uses'=>'Course\CourseController#index'));
//Delete course data
Route::get('/users/programs/course/{$id}/delete', array('as'=>'course.delete', 'uses'=>'Course\CourseController#delete'));
//Create course data
Route::post('/users/programs/course/create', array('as'=>'course.create', 'uses'=>'Course\CourseController#createCourse'));
//Edit course data
Route::get('/users/programs/course/{$id}/edit', array('as'=>'course.edit', 'uses'=>'Course\CourseController#editCourse'));
//Save editted course data
Route::put('/users/programs/course/{$id}/saveEdit', array('as'=>'course.saveEdit', 'uses'=>'Course\CourseController#saveEdit'));
});
I'm guessing that you are using DELETE in your route, which wouldn't work with an a link. You'd need to create a form and spoof the DELETE. You can find more about doing it here.
Alternatively, you can change Route::delete() to Route::get(), but this isn't recommended.
I think this could be do to with your triple braces. Try {{ action('Track\TrackController#create') }} instead.
More information read this link
Try this:
{!! action('track.delete',[$itemTrack->trackCode]) !!}
From documentation:
"If the method accepts route parameters, you may pass them as the second argument to the method:
$url = action('UserController#profile', ['id' => 1]);"
I guess 'id' wasn`t defined properly. Try this:
action('Track\TrackController#delete',['id' => $itemTrack->trackCode])
Replace delete Anchor tag with this:-
<a href="{{ url('users/programs/track/'.$itemTrack->trackCode.'/delete') }}" title="Delete" onclick="return confirm('Are you sure you want to delete this track : {{{$itemTrack->trackCode.' - '.$itemTrack->trackName }}}?')">
And change the delete Route:-
Route::match(['get', 'post'], '/users/programs/track/{id?}/delete', 'Track\#TrackController#delete');
Hope it Helps!

Categories