Laravel how to properly pass data to href - php

sorry if the question is kind of newbie. I am new to php and laravel, still trying to learn through tutorial.
I am trying to pass the 'No' in my database to the url, so that the url when I clicked on Daftar, it will show
http://127.0.0.1:8000/search/{No}
Webpage designed
I did try to put it this way in my href tag but did not manage to get the result I want
here is my code
search.blade.php
#if(isset($namelist))
<table class="table table-hover">
<thread>
<tr>
<th>No</th>
<th>Nama</th>
<th>ID</th>
<th>Tindakan</th>
</tr>
</thread>
<tbody>
#if(count($namelist) > 0)
#foreach($namelist as $nama)
<tr>
<td>{{ $nama->No }}</td>
<td>{{ $nama->Name }}</td>
<td>{{ $nama->ID }}</td>
<td>
<a href="search/".$nama[No]>DAFTAR</a>
</td>
</tr>
#endforeach
#else
<tr><td>Tiada rekod ditemui, sila daftar secara manual di kaunter pendaftaran</td></tr>
#endif
</tbody>
</table>
#endif
</div>
</div>
</div>
</body>
</html>
searchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class searchController extends Controller
{
function search(request $request){
if(isset($_GET['query'])){
$search_text = $_GET['query'];
$namelist = DB::table('namelist')-> where ('ID','LIKE','%'.$search_text.'%')->paginate(100);
return view('search',['namelist'=>$namelist]);
}
elseif(isset($_GET['query'])){
$search_text1 = $_GET['query'];
$namelist = DB::table('namelist')-> where ('No','LIKE','%'.$search_text1.'%')->paginate(100);
return view('search',['namelist'=>$namelist1]);
}
else{
return view('search');
}
}
}
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\searchController;
use App\Http\Controllers\daftar;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
route::get('/search',[searchController::class, 'search'])->name('web.search');
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Thank you

You have multiple ways to do that. In my opinion, the simplest way would be
DAFTAR.
Actually, what you have already done. Only with the Bladesyntax. And there is a small mistake in your example. Namely, your double quotes. <a href="search/".$nama[No]>DAFTAR</a> should be:
DAFTAR or better DAFTAR.
For the sake of completeness. the most elegant way would be to work with components.

Try this
<td>
DAFTAR
</td>
Enter the variable at given_variable_here above.
Also, you did not prepare the route to accept the passed variable in your web.php. This can be corrected like this:
Route::get('/search/{No}',[searchController::class, 'search'])->name('web.search');
Lastly, I'm not too sure about capitalizing the 'N' in the No you want to use. Should you have problems, start by placing these in lowercase. And if you're using VS Code make sure to add the extensions Laravel Extra Intellisense, Laravel Blade Snippets and Laravel Snippets. They are a great help. Let me know if this helps.

Related

ErrorException Undefined variable | Laravel , php

i'm new to Laravel.
I have trouble in showing data to a view page with this error:
ErrorException
Undefined variable $ikus (View: D:\XAMPP\htdocs\SKP-PA-BKT\resources\views\iku.blade.php)
And Laravel give me solution:
$ikus is undefined
Here is code in iku.blade.php :
#extends('layouts.sidebar')
#section('content')
<section class="main-panel">
<div class="container">
<div class="section-title">
</div>
<div class="row">
<div class="col-md-12">
<div class="table-wrap">
<table class="table table-responsive-xl">
<thead>
<tr>
<th>No </th>
<th>Opsi</th>
</tr>
</thead>
<tbody>
<tr class="alert">
#foreach ($ikus as $iku)
<td>{{ $iku->id }}</td>
#endforeach
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
#endsection
Here's code in IkuController.php
<?php
namespace App\Http\Controllers
use App\Models\Iku;
use Illuminate\Http\Request;
class IkuController extends Controller
{
public function getIku()
{
$ikus = Iku::all();
//dd($ikus);
return view('iku', compact('ikus'));
}
}
And here's in web.php
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\IkuController;
Auth::routes();
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/indikator-kinerja', [IkuController::class, 'getIku'])->name('iku');
It seems the $ikus variable from IkuController.php file can not be accessed by iku.blade.php file.
I have looked for solutions and most of what i've found is to add code like this:
return view ('layouts.index')->with(['features' => $features]);
or like this one:
return view ('layouts.index', compact('features'));
in IkuController.php file.
I have added it as written above. But i still get the same error. Is there anything left?
Thanks in advance.
This is most likely because your view is cached, you most likely ran the command
php artisan optimize
So just clear your view cache by doing:
php artisan view:clear
For the future, you can always see what is being cached by doing
php artisan about

Problem with displaying data that I want to delete with many to many relationship in Laravel

I have many to many relationship between users and products table and I set up a view (welcome.blade.php) that when I click on the product name, which is a link, it is supposed to redirect me to page where my delete form is so I can delete that particular product, but I get 404 not found page. I suspect that error is somewhere in my routes but I can't seem to find the problem. Also when I click on some product my url says project/destroy/1 which I think is good. Here is my code:
web.php:
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/store', 'HomeController#store')->name('store');
Route::delete('/destroy/{$id}', 'HomeController#destroy')->name('destroy');
destroy.blade.php:
<div class="col-md-12">
<form action="destroy/{{ $product->id }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
welcome.blade.php:
#if($products)
<table class="table">
<thead>
<th>#</th>
<th>Product Name</th>
<th>Owner Of The Product</th>
<th>Created At</th>
</thead>
<tbody>
#foreach ($products as $product)
<tr>
<td>{{ $product->id }}</td>
<td>
{{ $product->files }}
</td>
<td>
#foreach ($product->users as $user) {{ $user->name }}
#endforeach
</td>
<td>{{ date('M j, Y', strtotime($product->created_at)) }}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
HomeController.php:
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class HomeController extends Controller
{
public function destroy(Product $product)
{
$product->users()->detach();
$product->delete();
return view('destroy');
}
}
You defined the following route in your file.
Route::delete('/destroy/{$id}', 'HomeController#destroy')->name('destroy');
This creates a DELETE route. DELETE routes are meant to be accessed by APIs. Links in anchor tags use GET routes. Clicking on
{{ $product->files }}
makes the router try and match GET /destroy/{$id} which is not defined, so it throws either an exception if debug is on or a 404 if not. You can see this in action by looking at the network tab of your browser's developer console.
Unless you add another GET route, you'll keep getting 404s.
Route::get('/destroy/{$id}', 'HomeController#destroy')->name('product.destroy-form');
will make the following link work.
{{ $product->files }}
Also, in the destroy method you're returning the view without passing any variables but in destroy.blade.php you seem to be using $product. Don't forget to add it!
You are nearly there, you just have a step too many.
Good call on the form and using the delete method, this is absolutely what you are supposed to do
However where you are going wrong is in using the link to go to a separate page with the form on to delete. You are better using a little javascript so the link submits a hidden form from the link.
<a onclick="document.getElementById('delete-form-{{$product->id}}').submit();}">{{ $product->files }}</a>
<form id="delete-form-{{$product->id}}" action="{{ route('destroy', ['id' => $product->id]) }}" method="POST" style="display: none;">
#csrf
#method('delete')
</form>
You can do the method you have but you need an additional route::get request to a page that loads the form and then you can submit the form on that page to delete.
I think it is because to delete a product using a new page the first thing to do is navigate to that page which you are not doing. You are instead going directly to the delete function using this
Route::delete('/destroy/{$id}', 'HomeController#destroy')->name('destroy');
You need to define a route that lets you go to that page first which u can do by creating a route like this:
Route::get('/delete/{$id}', 'HomeController#delete')->name('delete');
You should create a new function delete in the HomeController that just returns the destroy.blade.php. Something like this.
$product= Product::find($id);
return view('destroy')->with('product', $product);
where $id is the product id and Product is the model that you are using.

Fetching data from Database in Laravel

I want to fetch data from database table named 'users' and display the output in a table.
I have written below code but it's not working.
I am using Laravel 5.5
#extends('layouts.app')
#section('content')
<div class="container">
<h2>Admin Panel</h2>
<p>Data of the Registered Users.</p>
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
$users = DB::table('users')->select('id','name','email')->get();
#foreach($users as $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
Error: Undefined Variable: users
The problem is that you're trying to mix PHP within your (Blade) template. Although it is possible to do so with #php directives, this is bad practice: your view should not contain any business logic.
Ideally you want to pass this data from your controller. It should look something like this:
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
return view('some-view')->with('users', $users);
}
}
Read more on passing data to views here.
You are doing it all wrong, the point of MVC design is to have your controllers do the application logic, your views to represent a representation of that data and models to contain the data you need, in your case you are missing the point completely by using DB::table inside of your view, so here is an example code which you might need to correct a bit:
The example below doesn't show MVC pattern since the data is passed from inside a closure of a route
web.php
Route::get('/', function () {
$users = DB::table('users')->select('id','name','email')->get();
return view('VIEW-NAME-HERE', compact('users'));
});
view.blade.php
#foreach($users as $user)
{{ $user->id }} {{ $user->name }} {{ $user->email }}
#endforeach
Change VIEW-NAME-HERE with the name of your view file, for example index or users.index
You Are using php in blade file
first make controller
for controller run a command in terminal
php artisan make:controller usercontroller
then write this:
class usercontroller extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
$data = compact('users')
return view('your-view-name')->with('$data');
}
}

Laravel Variable Not Passing Through

I'm an absolute beginner and I'm trying to do a CRUD in Laravel, but I can not figure it out why my variables aren't being passed over to the view so I can have a dynamic display of them in the table.
My "routes" work fine.
Then my controller
public function getHome()
{
$results = Crud::index();
return view('pages/home', ['results' => $results]);
}
Calls my "Crud" model
class Crud extends Model
{
public static function index()
{
return $results = DB::table('data')
->whereNotNull('id')
->get();
}
}
And goes to my view as seen in the controller
#extends('main')
#section('title', '| Home')
#section('content')
<div class="container">
#include ('partials/_jumbotron')
<table class="table table-inverse">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
#if(!empty($results))
#foreach($results as $result)
<tr>
<td scope="row">$result->$id</th>
<td>$result->$first_name</td>
<td>$result->$last_name</td>
<td>$result->$username</td>
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
#endsection
Thanks for the help in advance...I'm losing my mind
And sorry If I wasn't specific enough..
Edit1: I did as you say, but I'm still not outputing data to my table? Is there anything else wrong in the stated code or is the bug somewhere deeper?
Edit2: Thanks everyone for the pointed out mistakes - blade {{ }} and object properties
$object->propertie not $object->$propertie
When I fixed those mistakes which were obviously denying the output I remembered that I have an empty database.. Case Closed - Thanks everyone for the help
You're not printing the variables. You're printing literals.
If you want to print the variables (echo them) in blade files, you need to wrap them in curly brackets. Also there's not $ when you want to display an object attribute. Like that:
#foreach($results as $result)
<tr>
<td scope="row">{{ $result->id }}</th>
<td>{{ $result->first_name }}</td>
<td>{{ $result->last_name }}</td>
<td>{{ $result->username }}</td>
</tr>
#endforeach
I am a beginner too, I thought maybe you might want to try this as well
public function getHome()
{
$results = Crud::index();
return view('pages/home', compact('results'));
}
But before anything else make sure if your code is actually returning your data from DB using
dd($results)
The first of all cleaner will be using laravel with function for example
return view('pages/home')->with('results', $results);
Next you try to get $result->$first_name it didint working becouse first_name is not variable, laravel return object so you can get first_name like that:
{{$result->first_name}}

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