How to populate database values in table - php

I'm trying to fetch my records in my users table and populate them in table if the input is correct using Raw SQL Queries. Trying this convert from SQL to Laravel Queries:
SELECT * FROMusersWHERE username = 'shadow'
Unfortunately it gives me a error.
Undefined variable: users (View: C:\Users\JohnFrancis\LaravelFrancis\resources\views\account\search.blade.php)
Controller:
User is my Model which has a protected $table = 'users which is my database.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Requests;
use DB;
class AccountController extends Controller
{
public function getEmployee()
{
return view ('account.search');
}
public function postEmployee(Request $request)
{
$this->validate($request, [
'username' => 'required|alpha|max:20',
]);
$username = $request['username']; //Input will be passed to $request array. Accessing search field.
$user = new User();
$user = DB::select('select * from users where username = ?', [1]);
return view ('account.search', ['user' => 'myuser']);
}
}
View:
#section ('content')
<div class = "col-md-10">
<form class = "form-vertical" role = "form" method = "post" action = "{{ route ('account.search') }}">
<div class = "form-group {{ $errors->has('username') ? ' has-error' : '' }}">
<label for = "username" class = "control-label">Search</label>
<input type = "text" name = "username" class = "form-control" placeholder = "Find people">
#if ($errors->has('username'))
<span class = "help-block">{{ $errors->first('username') }}</span>
#endif
</div>
<div class = "form-group">
<button type = "submit" class = "btn btn-default">Search</button>
</div>
<input type = "hidden" name = "_token" value = "{{ Session::token() }}">
</form>
<table class = "table">
<br>
<thead>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Middlename</th>
<th>Email</th>
<th>Username</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach ($user as $myuser)
<tr class = "success">
<td>{{ $myuser->id }}</td>
<td>{{ $myuser->first_name }}</td>
<td>{{ $myuser->last_name }}</td>
<td>{{ $myuser->middle_name }}</td>
<td>{{ $myuser->email }}</td>
<td>{{ $myuser->username }}</td>
<td></td>
<td>
<button type = "submit" class = "btn btn-warning">Update</button>
<button type = "submit" class = "btn btn-danger">Archive</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
Routes:
Route::get('/search',
[
'uses' => '\App\Http\Controllers\AccountController#getEmployee',
'as' => 'account.search',
]);
Route::post('/search',
[
'uses' => '\App\Http\Controllers\AccountController#postEmployee',
]);

This should do what you want:
$user = User::where('username', $username)->get();
if ($user->isEmpty()) {
dd('Failed');
else {
dd('Success');
}

If you are using a model, there is no need for DB::select. You would find a User by their username like so:
$user = User::where('username', '=', (the username))->get();

Related

Eloquent query on relationship table

Hello i have two models Adress and Kontokorrent they have a one to one relationship. I would like to make a search function and search after Adress and Kontokorrent columns
My models:
Adress Model
class Adress extends Model
{
protected $table = "Adressen";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchAdress($query, $searchTerm)
{
return $query->where('LieferOrt', 'LIKE', '%'.$searchTerm.'%')
->orWhere('Name1', 'LIKE', '%'.$searchTerm.'%')
->orWhere('LieferStrasse', 'LIKE', '%'.$searchTerm.'%');
}
public function kontokorrent()
{
return $this->hasOne(Kontokorrent::class, 'Adresse');
}
}
Kontokorrent Model
class Kontokorrent extends Model
{
protected $table = "Kontokorrent";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchKto($query, $searchTerm)
{
return $query->where('Kto', 'LIKE', '%'.$searchTerm.'%');
}
public function adress()
{
return $this->belongsTo(Adress::class, 'Adresse');
}
}
Controller
class AdressesController extends Controller
{
public function index(Request $request)
{
$searchTerm = $request->input('searchTerm');
$adresses = Adress::whereHas('kontokorrent', function($query) use($searchTerm) {
$query->where('KtoArt', 'D')
->searchKto('K75688'); // this is working
// -> searchKto($searchTerm); this is NOT working
})->orderBy('Name1')
->searchAdress($searchTerm)
->paginate(60);
return view('adresse.index', compact('adresses', 'searchTerm'));
}
}
The search function in Adress model is working. Now i would like to search after the customer ID (Kto) in Kontokorrent. So i made a scope in Kontokorrent and chain it to the contoller search function.
->searchKto('K75688') .... this is working i get a result
->searchKto($searchTerm) .... this is not working when i entry the customer id in my input field and hit enter. I get a 0 row table.
View
#section('content')
<div class="row">
<div class="col-xs-12 col-md-12">
<form role="search" method="GET" action="/adresses">
<div class="input-group">
<input type="text" class="form-control" name="searchTerm" value="{{ isset($searchTerm) ? $searchTerm : '' }}" placeholder="Suche nach Name, Straße, Ort">
<div class="input-group-btn">
<button type="submit" class="btn btn-search btn-default">
Suchen...
</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Straße</th>
<th>Ort</th>
<th>PLZ</th>
<th>Land</th>
</tr>
</thead>
<tbody>
#if(count($adresses) > 0)
#foreach($adresses as $adress)
<tr>
<th scope="row">{{ $loop->iteration }}</th>
<td>
{{$adress->Anrede}} {{ $adress->Name1}}
#if($adress->kontokorrent)
<small>{{ $adress->kontokorrent->Kto }}</small>
#endif
</td>
<td>{{ $adress->LieferStrasse }}</td>
<td>{{ $adress->LieferOrt }}</td>
<td>{{ $adress->LieferPLZ }}</td>
<td>{{ $adress->LieferLand }}</td>
</tr>
#endforeach
#else
<tr><td colspan="6" class="text-center">Kein Eintrag gefunden.</td></tr>
#endif
</tbody>
</table>
</div>
</div>
{{ $adresses->appends(['searchTerm' => $searchTerm])->links() }}
#endsection
I don't understand why I get an empty table.

Call to a member function delete() on null / AdminHomeController.php line 26:

Using the multi_auth from laravel 5.3 im trying to make a delete/edit/update button.
Im trying to delete an user from the admin dashboard retrieving information from the users table.
Actually my first problem is with the destroy function.
This is my destroy route:
Route::get('{id}',[
'as' => 'admin.destroy',
'uses' => 'AdminHomeController#destroy'
]);
This is my controller from admin:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AdminHomeController extends Controller
{
public function __construct()
{
$this->middleware('admin.user');
}
public function index()
{
$users = User::all();
return view("admin-home")->with('users', $users);
}
public function destroy($id)
{
$users = User::find($id);
$users->delete();
Flash::error('El usuario ' . $users->name . '$ ha sido eliminado con exito!');
return redirect()->route('admin-home');
}
}
View with delete button:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="col-sm-offset-2 col-sm-8">
#if (count($users) > 0)
<div class="panel panel-default">
<div class="panel-heading">
Todos los Usuarios
</div>
<div class="panel-body">
<table class="table table-striped user-table">
<thead>
<th>Nombre:</th>
<th> </th>
<th>Email:</th>
<th> </th>
<th>Acciones:</th>
<th> </th>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td> </td>
<td>{{ $user->name }}</td>
<td> </td>
<td>{{ $user->email }}</td>
<td> </td>
<td>
<i class="glyphicon glyphicon-trash" aria-hidden="true"></i>
</td >
<td>
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
</td>
<td> </td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
</div>
</div>
</div>
</div>
#endsection
Thank you!
Check $id in
$users = User::find($id);
$users->delete();
Object $users is null because user didn't found in database or $id is incorrect
After playing around with the code i found this usefull:
In the view i had 2 buttons the delete and the edit ones, i changed:
{{ route('users.destroy', $user->id) }}
{{ route('users.edit', $user->id) }}
for:
{{ url('users.destroy', $user->id) }}
{{ url('users.edit', $user->id) }}
And now i can see the buttons without any problems, the issue now is the same as before, the function destroy gives me an error.
This is the route that causes the error:
Route::get('{id}',[
'as' => 'admin.destroy',
'uses' => 'AdminHomeController#destroy'
]);
Error: No query results for model [App\User].
This is my User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
And still can't find the issue.. #edwardstock

Laravel: Eloquent returning an object I can't iterate over

I have a mySQL DB schema like this:
table RECIPES:
int id, PK;
int salesman_id;
int doctor_id;
date order_date;
int status;
table RECIPE_STATUS:
int id, PK;
int recipe_status_code;
varchar recipe_status_name;
In Laravel I have the following php classes:
AdminRecipesController.php
namespace RatCMS\Controllers;
use App\Http\Controllers\Controller;
use Auth;
use RatCMS\Models\Recipes;
use RatCMS\Models\RecipeStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class AdminRecipesController extends Controller
{
public function index()
{
$recipes = Recipes::with('recipeStatus')->get();
return view('admin.recipes.news', compact('recipes'));
}
}
Recipes.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class Recipes extends Model
{
protected $table = 'RECIPES';
protected $fillable = ['salesman_id', 'doctor_id', 'order_date', 'status'];
public function recipeStatus() {
return $this->hasOne(\RatCMS\Models\RecipeStatus::class, 'recipe_status_code', 'status');
}
}
RecipeStatus.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class RecipeStatus extends Model
{
protected $table = 'RECIPE_STATUS';
protected $fillable = [];
public function recipes() {
return $this->belongsTo(\RatCMS\Models\Recipes::class);
}
}
blade view
<div class="box-body">
#include('admin.partials.session_success')
#if($recipes->isEmpty())
<p class="text-center">No recipes available.</p>
#else
<table class="table table-bordered">
<tr>
<th style="width: 10px">#</th>
<th>Salesman</th>
<th>Doctor</th>
<th>Date</th>
<th>Status</th>
<th style="width:100px">Actions</th>
</tr>
#foreach($recipes as $recipe)
{{ $recipe }}
<tr>
<td>{{ $recipe->id }}</td>
<td>{{ $recipe->salesman_id }}</td>
<td>{{ $recipe->doctor_id }}</td>
<td>{{ $recipe->order_date }}</td>
<td>{{ $recipe->recipe_status->recipe_status_name }}</td>
<td>
<form style="display: inline-block" action="{{ url('admin/recipes/' . $recipe->id) }}" method="POST">
{{ csrf_field() }}
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger"><i class="fa fa-close" aria-hidden="true"></i> Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
#endif
</div>
When I do {{ $recipe }} in the view, I get the following result:
{"id":1,"salesman_id":"4","doctor_id":"3","order_date":null,"status":"0","recipe_status":{"id":1,"recipe_status_code":"0","recipe_status_name":"Not Recieved"}}
so there is some data being return by Eloquent regarding the recipe status (Not Recieved text), but when I do {{ $recipe->recipe_status }} it fails every time. Even $recipes['recipe_status'] is no help.
Could someone help? Thanks
Relationship should be belongsTo():
public function recipeStatus() {
return $this->belongsTo(\RatCMS\Models\RecipeStatus::class, 'status', 'recipe_status_code');
}
With correct relationship your code will add relationship data to collection, so you'll be able to get status:
$recipe->recipeStatus->recipe_status_name

What's the cause Undefined property: stdClass?

I don't know what this error cause. I didn't change anything in my codes. But when I go to my search view. It always returns me the undefined property error. This error cause when I tried to foreach all my columns in my table data. I already solve this error not once. Because it cannot find the $id of selected options. But this time I can't fix it.
Error:
Undefined property: stdClass::$id (View: C:\Users\JohnFrancis\LaravelFrancis\resources\views\document\show.blade.php)
View
show.blade.php - This view will list all the values in my tables.
#section ('content')
<div class = "col-md-12">
<table class = "table">
<thead>
<tr>
<th>Title</th>
<th>Content</th>
<th>Category</th>
<th>Sender</th>
<th>Date Received</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($documentLists as $list)
<tr class = "info">
<td>{{ $list->title }}</td>
<td>{{ strip_tags(substr($list->content, 0, 50)) }} {{ strlen($list->content) > 50 ? "..." : '' }}</td>
<td>{{ $list->category_type }}</td>
<td>{{ $list->username }}</td>
<td>{{ date('M j, Y', strtotime($list->dateReceived)) }}</td>
<td>
<button type = "submit" class = "btn btn-info">Read</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
read.blade.php - This where it will redirect to the current view that selected.
<!--DOCUMENT CONTROLLER-->
<div class = "col-md-6">
<form class = "vertical">
<div class = "form-group">
<textarea id = "content">{{ $documentLists->content }}</textarea>
</div>
<div class = "form-group">
<button type = "submit" class = "btn btn-success">Approve</button>
</div>
</form>
</div>
Controller
//SHOW
public function showDocuments()
{
$documentLists = DB::table('document_user')->select('documents.title', 'documents.content', 'categories.category_type', 'users.username', 'document_user.dateReceived')
//Table name //PK //FK
->join('users', 'users.id', '=', 'document_user.sender_id')
->join('documents', 'documents.id', '=', 'document_user.document_id')
->join('categories', 'categories.id', '=', 'documents.category_id')
->where('sender_id', '!=', Auth::id())
->where('user_id', '!=', Auth::id())->get();
//VIEW
return view ('document.show')->with('documentLists', $documentLists);
}
//READ
public function readDocuments($id)
{
//Find the document in the database and save as var.
$documentLists = Document::find($id);
return view ('document.read')->with('documentLists', $documentLists);
}
routes
Route::get('/show',
[
'uses' => '\App\Http\Controllers\DocumentController#showDocuments',
'as' => 'document.show',
'middleware' => 'auth',
]);
Route::get('/receive/documents/{id}',
[
'uses' => '\App\Http\Controllers\DocumentController#readDocuments',
'as' => 'document.read',
'middleware' => 'auth',
]);
In below you are not selecting id
$documentLists = DB::table('document_user')->select('documents.title', 'documents.
but calling in your blade {{ route ('document.read', $list->id) }}
$documentLists = DB::table('document_user')->select('documents.id','documents.title', 'documents.content', 'categories.category_type', 'users.username', 'document_user.dateReceived');
You need to select the column documents.id.But you have missed it

can't access the variable i passed from controller to my view in laravel 4.2

i have a view that contains a form. the form's url is the address of view that the form is in it.
in controller i pass a variable to the view when the user hit the button in the form.
but my view has an error says the variable i passed to it is undefined.
here is my code
my view:
#extends('layouts.master')
#section('content')
<?php
$category = Category::lists('name','name');
$priority = Priority::lists('name','name');
$lesson = Lesson::lists('name','name');
$count = 1;
?>
{{ Form::open(array('action' => 'createQuizController#find', 'method' => 'POST', 'id' => 'search_question')) }}
<div>
{{ Form::label('quiz_cat', 'نام دسته بندی') }}
{{ Form::select('quiz_cat', array('/'=>'انتخاب کنید')+$category, null, ['id' => 'cat_select']) }}
</div>
<div>
{{ Form::label('quiz_less','نام درس') }}
{{ Form::select('quiz_less',$lesson, null, ['id' => 'les_select']) }}
</div>
<div>
{{ Form::label('quiz_prio','سطح سوال') }}
{{ Form::select('quiz_prio',array('/'=>'انتخاب کنید')+$priority, null, ['id' => 'prio_select']) }}
</div>
<div>
{{Form::label('date_start','تاریخ شروع')}}
{{Form::input('date','date_start',null,array('id' => 'date_start'))}}
</div>
<div class='form-group'>
{{ Form::submit('جستجو', ['class' => 'btn btn-primary']) }}
</div>
{{ Form::close() }}
<iframe width="690px" height="300px" scrolling="yes">
{{ Form::open(array('method' => 'POST', 'id' => 'add_question')) }}
<div class="col-lg-10 col-lg-offset-1">
<div class="table-responsive" id="question_table">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ردیف</th>
<th>عنوان سوال</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach ($res as $quiz)
<tr>
<td align="center" width="100px">
<?php echo $count++; ?>
</td>
<td align="center" width="200px">{{ $quiz->title }}</td>
<td align="center" width="200px"><input type="checkbox" name="select_question[]" id="{{ $quiz->lesson_id }}" value="{{ $quiz->id }}"></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
{{ Form::submit('افزودن', ['class' => 'btn btn-primary']) }}
{{ Form::close() }}
</iframe>
#stop
my controller:
<?php
class createQuizController extends BaseController {
public function find()
{
$prio = Input::get('quiz_prio');
$res1 = DB::select("select id from priority pr where '$prio' = pr.name");
$r1 = $res1[0]->id;
$cat = Input::get('quiz_cat');
$res2 = DB::select("select id from categories cat where '$cat' = cat.name");
$r2 = $res2[0]->id;
$les = Input::get('quiz_less');
$res3 = DB::select("select id from lesson less where '$les' = less.name");
$r3 = $res3[0]->id;
$sdate = Input::get('date_start');
$res = DB::select("select * from quiz where categories_id='$r2' and lesson_id='$r3' and priority_id='$r1' and date_start='$sdate'");
return View::make('cquiz')->with('res',$res);
}
public function addQuestion()
{
$a = array();
$a[] = Input::get('select_question');
var_dump($a[]);
/*foreach($a as $b) {
$c = DB::select("select name from lesson where '$b'=id" );
var_dump($c);
}*/
}
}
my route:
Route::post('/cquiz/','createQuizController#find');
Route::post('/addQuestion/','createQuizController#addQuestion');
try this:
return View::make('cquiz')->withRes($res);
and in the view you can access '$res' (or {{ $res }} etc)

Categories