Laravel input feature didn't work and show error 404 - php

Hello everyone. i just learn laravel this month, and i get some problem that haven't solved since yesterday.
So i want to make a feature where i input a token and submit it, and the page will redirect to view page. the token will used by the controller to find row of data that match the token and will return the data to view page. i already (seems) succeed made the feature. the value of input is (should be) the token, initialized with {$kodeunik}, but what's confused me is when i input the form with {$id} the feature works, but if i inputted with {$kodeunik}, it didn't works. (shows 404) any solution? what should i do? Thanks
For info: ({$id} is the primary key and {$kodeunik} is the unique key)
this is the Controller.
public function cek()
{
return view('cek');
}
public function show(Request $request)
{
$kodeunik = urlencode($request -> input('kodeunik'));
$blog = blog::find($kodeunik);
if (!$blog)
{
abort(404);
}
return view('tampil', ['blog' => $blog]);
}
This is the Form view
<form method="get" action="/">
<div class="form-group row">
<label for="kodeunik" class="col-md-4 col-form-label text-md-right">Kode Unik</label>
<div class="col-md-6">
<input id="kodeunik" type="text" name="kodeunik">
</div>
</div>
<input type="submit" name="submit" value="cek">
{{csrf_field()}}
<input type="hidden" name="_method" value="get">
this is the Show View
#section('content')
<h1>Detail Laporan kau</h1>
<table class="maxw600 no-padding">
<tr><td><b>Status: </b></td><td>{{ $blog -> tag}}</td><br>
<tr><td><b>Nama: </b></td><td>{{ $blog -> nama}}</td></tr>
<tr><td><b>Bagian: </b></td><td>{{ $blog -> bagian}}</td></tr>
<tr><td><b>Telp/Ext: </b></td><td>{{ $blog -> telp}}</td></tr>
<tr><td><b>Email: </b></td><td>{{ $blog ->email}}</td></tr>
<tr><td><b>Subjek: </b></td><td>{{ $blog -> title}}</td></tr>
<tr><td><b>Deskripsi: </b></td></tr>
</table>
<p>{{ $blog -> description }}</p>
<p>{{ $blog -> tanggapan }}</p>
#endsection
This is the Route
Route::get('/cek', 'UserController#cek'); //this is route for the form view
Route::get('/', 'UserController#show'); //this is route for showing the result

Note: Eloquent will also assume that each table has a primary key column named id. You may define a primaryKey property to override this convention. Likewise, you may define a connection property to override the name of the database connection that should be used when utilizing the model.
In your case, when you pass id it works because laravel know's that its the default primary key in your table. Now when you pass kodeunik, laravel will still find kodeunik in id field of your table.
So here are some solution how to solve this.
first : change the primary key of your table by putting this code in your model
protected $primaryKey = 'kodeunik_field';
Second : just use where clause to get a result, like this
$blog = blog::where('kodeunik_field', $kodeunik)->get()->first();

Related

Passing Collection from Blade to Controller

I am working on an application and need to pass data from Blade back to the controller
I am passing the data to the blade like this
$reports = $query->paginate();
return view('admin.report', compact('reports'));
this works fine, however I want to have a button to pass $reports collection to this function
public function exportToCSV(Document $reports)
this is going to create a CSV file that will be downloaded including every entry from $reports
I have doing a lot of googling on this and have even have someone help me try to figure it out to no avail.
One way to achieve this would be with a form. You can have a hidden input, with the collection as the value. You would define a route for the form to POST to, and call your function from the route in web.php.
<form action="/route/to/wherever/" method="POST">
{{ csrf_field() }}
<input type="hidden"
name="key"
value="{{ $collection }}"
>
</form>
Be sure to add a submit button. In your method you would receive the collection like:
public function myFunction(Request $request){
$data = $request->key;
}

why am i getting null value from my database in laravel when trying to find specific user?

Am trying to display information of a specific student in my database using student ID. I seem to get null value yet the student exist in the database. i seriously do not know why am getting this null value.
this is what i did
public function showResult(Request $request, $std_id)
{
$user = Student::find($std_id);
if (empty($user)) {
return redirect('/user')
}
$academic = $request->input('academic_year');
$std = $request -> input('studentID');
$results = DB::table('students')
->select('*')
->join('results', 'students.std_id', 'results.student_results_id')
->where('student_results_id', '=', $std)
->where('academic_year', '=', $academic)
->get();
return view('resultsdisplay',[
'results' => $results,
]);
}
}
This is my Route:
Route::get('/student/resultshow/{std_id}', 'ResultsController#showResult');
My studentprofile.blade.php
<li class="list-group-item">
<form action="{{URL::to('/student/resultshow/{!! $studentprofilePage->std_id !!}')}}" method="GET" enctype="multipart/form-data">
<input type="text" name="studentID" value="{!! $studentprofilePage->std_id !!}" hidden="">
<input type="text" name="academic_year" placeholder="Academic year..">
<button>view</button>
</form>
</li>
A couple of things to test. First, check the $std_id variable as it comes into the method to make sure this is translating correctly from your form / route into the method.
public function showResult(Request $request, $std_id){
dd($std_id);
If this is a properly formed integer/id, check the database just to make sure that id is actually assigned within the students table, and it is not soft-deleted if you are using soft-deletes (deleted_at column).
If all good there, take a look at the Student model itself. Is the model pointing to the right table? Laravel assumes the table is named 'students'. If not, have you declared the table within the model?
public $table = 'mySpecialStudentsTableName';
Also, is the id type correct against what is coming in. IE I assume it is an integer, but if it is looking for a string / uuid, is that properly coming out of that $std_id variable?
Finally - your form is not sending the correct id:
<form action="{{URL::to('/student/resultshow/{!! $studentprofilePage->std_id !!}')}}"
Should be:
<form action="{{URL::to('/student/resultshow/'. $studentprofilePage->std_id)}}"

Laravel - delete specific post from logged in user

I'm trying to make a delete button on a post from a user that is logged in. The logged in user can see other peoples posts, and only delete his own. I already managed that the delete button only appears on his own posts. I think the problem is in the route in the view..
Controller:
public function destroy($id)
{
$post = Post::find($id);
$post->delete;
return view('/home', [
'posts' => $post
]);
}
view:
#if ($post->checkUser(Auth::user()))
<form action="{{ route('posts.destroy, $post') }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button>Delete</button>
</form>
#endif
Route:
Route::resource('posts', 'PostController');
Change $post->delete; to $post->delete(); because delete() method is a function. And if you use resource you should send request with delete method for call destroy method. but you can not do it from form because for support only post and get, another solution you can use hidden input and send with post method, <input name="_method" type="hidden" value="DELETE">
You need to specify post_id and user_id both.
public function destroy($id)
{
$user_id = Auth::user();
$post = Post::where('post_id', $id)->where('user_id',$user_id)-get();
$post->delete();
// do your rest of code
}
Change post_id and user_id name according to your table field name.
I think you should edit the route in your view to look like this,
route('posts.destroy, ['id' => $post->id]'), if that doesn't work check your named route again by doing php artisan route:list, and also try to post the full error for better understanding.

Cannot use object of type Illuminate\Database\Eloquent\Builder as array

i want view data with the specific id my post.
my controller is :
public function profile(){
$data = Admin::with(array(5,6));
return view('profile')->with('data',$data);
}
i want view post in id '5' :
<div class="content-about">
<p> {{ $data[5][post]}} </p>
</div>
and the other view i will post in id '6'
<div class="content-about">
<p> {{ $data[6][post]}} </p>
</div>
First, your query is incorrect. Model::with([...]) is eager loading specified relations. But Admin::with(array(5,6)) passing numeric values to the function, they are ignored as with() expects them to be a string naming your relations. So with(array(5,6)) actually does nothing, simply return the query instance.
To load your Admin with primary key 5 and 6, you need to use whereIn().
$data = Admin::whereIn('id', array(5,6))->get();
Now you have the result data set. Then you want to access the result item by primary key. The result data set $data is an instance of Illuminate\Database\Eloquent\Collection which support such feature via keyBy().
You want to access item by primary key id, so here is your code should look like.
$data = Admin::whereIn('id', array(5,6))->get()->keyBy('id');
Try this: Your data is an Array of object
Controller:
public function profile(){
$data = Admin::whereIn('id', [5,6])->get();
return view('profile')->with('data',$data);
}
In your view:
#foreach($data as $key => $post)
<div class="content-about">
<p> {{$post->id}} </p>
<p> {{$post->post}}</p>
</div>
#endforeach

Laravel displaying all posts with WHERE clause and pagenation in laravel

so i want to display post in my index page but only the posts that are reviewed by the admin. so i added another column in my database table post which is called "review" which is integer. So this is what i have in hand.
in my controller i have this
public function index()
{
$this->layout->content = View::make('partials.index',
array(
'posts' => Post::paginate(9)
));
}
and in my index page i have this
#section('content')
<div class="dashboard">
#foreach (array_chunk($posts->getCollection()->all(),2) as $row)
<div class="row">
#foreach($row as $post)
<article class="col-md-4 effect4" id="dash-box">
<p></p>
<c>{{$post->content}}</c><br>
<b>{{$post->title}}</b><br>
<d>posted..{{$post->created_at->diffForHumans()}}</d>
<hr>
</article>
#endforeach
</div>
#endforeach
<div class="page">
{{$posts->appends(Request::only('difficulty'))->links()}}
</div>
</div>
#stop
Help im newbie here i hope someone can help me out with this one hoping for a reply thanks
Just call:
Post::whereReview(1)->paginate(9);
Please read the documentation (and also the one for the query builder since these pages apply to Eloquent as well)
You can just add a where() call to the query:
$posts = Post::where('review', '=', 1)->paginate(9);
Or a shorter version (= is the default operator)
$posts = Post::where('review', 1)->paginate(9);
Or even with a dynamic method name:
$posts = Post::whereReview(1)->paginate(9);
Also you can use true instead of 1. Laravel will convert it:
$posts = Post::whereReview(true)->paginate(9);
There is also no need to do chunking that complicated:
#foreach (array_chunk($posts->getCollection()->all(),2) as $row)
You can just use the chunk method on any collection:
#foreach ($posts->chunk(2) as $row)

Categories