I have a project in laravel 4.
In my blade file i have:
<div class="col-sm-12">
Show more
</div>
I want to pass my limit and gap to the controller. In the controller i use Input::get('limit'); but i get back a null.
Even Input::all() returns null.
Any tips?
Thank you!
HTML(VIEW) CODE
Code for a tag
click ok
Form code
<form method="POST" action="{{url('submit/Parameters..')}}" method="post">
{{ csrf_field() }}
...
</form>
ROUTE CODE
route code with action
Route::get('user/{id}', function ($id) {
echo "id is : ".$id ;
});
route code for controller
Route::get('user/{id}', 'UserController#show');
CONTROLLERS CODE
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class ShowProfile extends Controller
{
public function index($id)
{
echo $id;
}
}
for more information you see following like
https://laravel.com/docs/5.4/controllers
and https://laravel.com/docs/5.4/routing
Try this:
<div class="col-sm-12">
Show more
And ensure that your route and controller passed params.
Route must be configured with dataLimit and dataGap params, and controller method must accept it.
Input is for forms. If you want to use anchors, you will have to pass parameters to url like this
<a href="/url?limit=12&gap=12" >Show more </a>
This makes them optional to your controller. You just need to get them with request().
$limit = request('limit');
$gap = request('gap');
Related
I have some posts on my index page, and each post has an edit button on it.
The problem is, I want the URL to be hungarian, but every time I change the function's name from edit to sth. else it gives me 404 error.
I show the posts with the following code:
#foreach($posts as $post)
<div class="card p-3">
<h3>{{$post->title}}</h3>
<small>Feltöltve: {{$post->created_at}}</small>
<h3>Szerkesztés</h3> I TRY TO CHANGE /EDIT TO STH. ELSE HERE
</div>
#endforeach
And here is my posts controller with the edit function:
public function edit($id) { I change edit here as well
$post = Post::find($id);
return view('elado.szerkeszt')->with('post', $post);
}
In web.php, I've
Route::resource('elado', 'PostsController');
Because you're using resource() method in your route declaration. Which will use by default there routes and control methods
[
'create',
'store',
'show',
'edit',
'update',
'destroy',
]
If you want to change the method name, declare the route on your own
Route::post('/change', 'PostsController#change');
you can exclude edit method from resource routes with except method like, then define new route with your custom edit method and put before resources routes:
Route::post('/elado/{id}', 'PostsController#sth');
Route::resource('elado', 'PostsController')->except([
'edit'
]);
So, i wish to set a variable which i will later append to the beginning of a resource's route, i'm currently using the following code:
{!!
$baseDestinationImage=asset("img/uploads/destinations/");
!!}
<img src="{!! $baseDestinationImage.'/'.$destination->Dimage !!}" alt="{{$destination->Dname}}">
The above works fine, the only issue here is that the variable $baseDestinationImage also gets echoed, what's the simplest way to set a variable without it being displayed in Laravel 5.6?
use in controller then..
public class YourController{
...
public function index()
{
...
$baseDestinationImage=asset("img/uploads/destinations/");
return view('your.blade.view', compact('baseDestinationImage'));
}
}
in Blade
<img src="{{ $baseDestinationImage }}" />
You shouldn't set variables in your Blade templates. Still, if you still want to do it, you can embed PHP code using the #php directive:
#php
$baseDestinationImage=asset("img/uploads/destinations/");
#endphp
You can do it using the eloquent Accessors and mutators
which allow you to format Eloquent attribute values when you retrieve or set them on model instances.
So your model should be like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class YourModel extends Model
{
public function getPhotoAttribute($photo)
{
return $photo ? asset('your/path/' . $photo) : '';
}
}
And on your blade you can use it like this:
{{ $object->photo }}
I am sort of new to the Laravel framework and I am building just a simple blog. I can create a blog, show a blog and show a overview of all blogs. Now I would like to delete a blog. So, I have created a delete button in my view with a route link which will pass also the id of the article. Then, in my routes file I specify a delete request and a controller method. In the method I find the id and try to delete the row with the id I specified in the route/view.
This doesn't work. Instead of activate the destroy/delete method it shows the article instead of deleting it and activates the show method instead of the delete method. Can somebody help me out, What do I wrong?
View.blade.php
<a href="{{route('nieuws.destroy', ['id' => $blog->id])}}" onclick="return confirm('Weet je dit zeker?')">
<i class="fa fa-trash"></i>
</a>
Route
Route::group(['middleware' => 'auth'], function () {
Route::get('/aanvragen', 'aanvragenController#index')->name('aanvragen.index');
Route::get('/logout' , 'Auth\LoginController#logout')->name('logout');
Route::get('/nieuws/toevoegen', 'blogController#create')->name('blogs.add');
Route::post('/nieuws/store', 'blogController#store')->name('nieuws.store');
Route::delete('/nieuws/{id}', 'blogController#destroy')->name('nieuws.destroy');
});
Route::get('/nieuws', 'blogController#index')->name('blogs.index');
Route::get('/nieuws/{blog}', 'blogController#show')->name('blogs.show');
Controller methods
Delete/Destroy
public function destroy($id) {
$blog = Blog::find($id);
$blog->delete();
return redirect('/nieuws');
}
Show
public function show(Blog $blog) {
dd('show');
return view('blogs.show', compact('blog'));
}
A delete() route requires you to POST your data.
HTML forms only supports GET and POST, other methods like DELETE, PUT, etc are not supported, that's why Laravel uses the _method to spoof methods which are not supported by HTML forms.
You do not want use GET in these cases, since someone can send a user the url (http://yoursite.com/blog/delete/1) in an IM or via email. The user clicks and the blog is gone.
Define your route as it would be when using resource controllers, so:
Route::delete('/nieuws/{id}', 'blogController#destroy')->name('nieuws.destroy');
And either use a form with the delete method:
// apply some inline form styles
<form method="POST" action="{{ route('nieuws.destroy', [$blog->id]) }}">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit">Delete</button>
</form>
Or do some javascript magic as the link SR_ posted in his comment on your OP.
One more thing, add some sort of validation in your destroy action. Right now when you provide a non-existing id or something else, you will get a 500 error, instead you want to have a 404.
public function destroy($id)
{
$blog = Blog::findOrFail($id);
$blog->delete();
return redirect('/nieuws');
}
I think you need to update your destroy function like:
public function destroy($id) {
$blog = DB::table('blog')->where('id',$id)->delete();
return redirect('/nieuws');
}
And update your view code like:
<a href="{{route('nieuws.destroy', [$blog->id])}}" onclick="return confirm('Weet je dit zeker?')">
<i class="fa fa-trash"></i>
</a>
Hope this work for you!
I'm also new to Laravel but I made it work through this way:
(I use 'Article' as the model's name and the resource "method" in the route stands for a bunch of useful routes including the route you wrote)
Controller:
public function destroy($id){
Article::find($id)->delete();
//$article = Article::find($id);
return redirect()->back()->withErrors('Successfully deleted!');
}
Route:
Route::resource('article','ArticleController');
However, I think the problem lies in the default definition of database's name of your model. Laravel will assume that you have a database named blogs since you have a model named "blog". Are you having the database's name right?
To use DELETE HTTP Verb, your form should consists of the POST method and settings the method_field('DELETE')
Example:
<form method="POST" action="{{ route('xxx.destroy', $xxx->id) }}">
{{ csrf_field }}
{{ method_field('DELETE') }}
</form>
I get this error that says, "No query results for the model [App\dummy]." I believe the problem is in the controller. When you submit the form it is supposed to trigger the function in the comment controller. This controller is new so, I believe the error is in here. That is when it stopped working. Here is the commentController file:
<?php
namespace App\Http\Controllers;
use App\Dummy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; //this one is for sql builders
use App\Comments;
use Illuminate\Http\RedirectResponse;
use DateTime; //to create a new date object you need to include this namespace
class commentController extends Controller
{
public function store(Dummy $post){
$date = new DateTime();
$timestamp = $date->getTimestamp();
$id = $post->id;
$post->addComment(request('body'));
return view('post', compact('post', 'timestamp', 'id'));
}
}
I tried making App\Dummy lowercase so it was App\dummy but still it didn't work. It still gives me the error.
Here is my dummy model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class dummy extends Model
{
protected $guarded = [];
public function comments(){
return $this->hasMany(Comments::class, 'post_id');
}
public function addComment($body){
$this->comments()->create(compact('body'));
}
}
Your error is that your class is called dummy buy you are using it as Dummy, so rename it both (file and class) to Dummy.
This class dummy extends Model to this class Dummy extends Model.
Remember that your file should be called Dummy.php too, not dummy.php
Change your model class name to Dummy and file name to Dummy.php.
Your main problem here is the route model binding. When you're trying to add a comment, the $post object is not getting resolved based on your route. You have bad a route setup or trying to add comment to a non existent post.
Basically the error message No query results for the model happens because of this code that the route model binding does for you.
$post = Dummy::findOrFail($id);
Try changing this
Route::post('post/{dummy}/comments', 'commentController#store');
public function store(Dummy $dummy)
The problem was in the form. The action attribute in the form was something like this:
<form class="col s12" action={{ url('/post/$id/comments') }} method="post">
I thought that would get the id because I compacted the id into the variable $id. But then I checked the url and noticed not a number but the actual word $id. So, here is the solution:
<form class="col s12" action={{ url('/post/' . $post->id . '/comments') }} method="post">
Just to let you guys know that when it said, "No query results for the model [App\dummy]." It meant that when I used this method from the dummy model which had this line of code:
public function comments(){
return $this->hasMany(Comments::class, 'post_id');
}
It couldn't find the primary key from the dummies table. Therefore couldn't connect with the foreign key which is the post_id from the comments table. So, it wasn't able to submit the new comment to the table for that unique blog post. This is the last part that submits the comment to the table:
public function addComment($body, $name){
$this->comments()->create(compact('body', 'name'));
}
by the way comments() is the method I created that i just showed before.
Conclusion
It pretty much stopped working in the web.php file(routing file) because it wasn't getting an id. Due to the mistake I made in the action attribute in the form that i explained before.
I am trying to build an application wich it will contain an admin dashboard where the admin will be able to CRUD Posts but also he will be able just to see User Submitted Posts.
On the other hand the guest will be able to just see the Posts, but he will be able to Create User Submitted Posts.
Until now I have managed to get the Posts functionallity working, but not for the User Submitted Posts.
My Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Usp;
class AdminUserPostsController extends Controller
{
public function index()
{
$userposts = Usp::orderBy('id', 'desc')->paginate(10);
return view('admin.userposts.archive')->withUsp($userposts);
}
public function show($id)
{
$userpost = Usp::find($id);
return view('admin.userposts.show')->withUsp($userpost);
}
}
My Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Usp extends Model
{
//
}
My Archive View
#extends('admin')
#section('dashboard-content')
<div class="col-md-8 offset-md-2">
<h1>Posts Archive</h1>
<hr>
</div>
#foreach ($userposts as $userpost)
<div class="col-md-6 offset-md-2">
<h3>Title: {{ $userpost->title }}</h3>
<hr>
</div>
#endforeach
#endsection
and My Routes(for the specific controller)
Route::get('/admin/userposts', 'AdminUserPostsController#index')->name('admin.userposts.archive');
Route::get('/admin/userposts/{id}', 'AdminUserPostsController#show')->name('admin.userposts.show');
I am getting the error that userposts variable is not defined, although I define it in my Controller. Anyone that can help ?
You should "transmit" your variables to your view. There are several ways to do this, but I'd say the most common is to use the "with compact". In your case, you should change this
return view('admin.userposts.archive')->withUsp($userposts);
To this
return view('admin.userposts.archive')->with(compact('userposts'));
How does it work :
compact("varname", [...])
returns an array with the keys being the variable name and the values being the variable values
And the with just transmits all the array to the view
PS :
compact('userposts')
Is exactly the same as this
['userposts' => $userposts]
If you want to use userposts variable, do this:
return view('admin.userposts.archive', compact('userposts');
Or this:
return view('admin.userposts.archive', ['userposts' => $userposts]);
Change this:
return view('admin.userposts.show')->withUsp($userpost);
to
return view('admin.userposts.show', array('userpost' => $userpost));
and try again. You can get $userpost on blade view like:
{{ $userpost }}
If it is an array, use foreach() to get all of its elements.