I am Using Laravel 5.2
Is There a Way To Get a Pagination Pretty URL in Laravel 5.2?
http://localhost:8000/backend/admin_user?page=10&page=1
And What I Would Like To Get,How generate Link Pretty Url:
http://localhost:8000/backend/admin_user/10/1
So you can try something like that:
Route::get('test/{page}', function ($page) {
return User::paginate(2, ['*'], 'page', $page);
});
You can achieve this with three simple steps.
Register the route:
Note the question mark, this makes the size and page values optional;
Route::get('backend/admin_user/{size?}/{page?}', ['uses' => 'BackendController#adminUser']);
Implement this function in your controller:
Note the default values, $size = 10, $page = 1. This makes sure that you don't get an error if you navigate to the url without the pagination.
<?php namespace App\Http\Controllers;
use App\Models\AdminUser;
use Illuminate\Pagination\LengthAwarePaginator;
class BackendController
{
public function adminUser($size = 10, $page = 1)
{
$collection = AdminUser::all();
$users = new LengthAwarePaginator($collection, $collection->count(), $size);
$users->resolveCurrentPage($page);
return view(backend.admin_user);
}
}
Use in your view like this:
<div class="container">
#foreach ($users as $user)
{{ $user->name }}
#endforeach
</div>
{{ $users->links() }}
Related
Is it possible to assign a blade template to a model?
Instead of doing this:
#php $contact = Contact::find(1); #endphp
#include('contact', ['contact' => $contact])
I'd like to just do:
#php $contact = Contact::find(1); #endphp
{{ $contact }}
But latter obviously just spits out the model in json.
It is possible with PHP's __toString() magic method: https://www.php.net/manual/en/language.oop5.magic.php#object.tostring
Let's make an example for default User.php model.
First, create a blade file for that model, lets create that as /resources/views/model/user.blade.php and a dummy component;
<h1>{{ $user->name }}</h1>
<p>{{ $user->created_at->diffForHumans() }}</p>
Now make this default __toString() for User model.
Add this to app/Models/User.php ;
/**
* #return string
*/
public function __toString(): string
{
return view('model.user', ['user' => $this])->render();
}
Now you can test it directly in your routes/web.php ;
Route::get('test', function () {
echo \App\Models\User::first();
});
Or try to echo it in any view as;
{!! $user !!}
You can't use {{ $user }} because you need that HTML tags, so you have to use it as {!! $user !!}
I'm building an admin panel in TALL (Laravel 7) + Turbolinks. One section only includes a Livewire component that shows a paginated table of Product elements and a search field (the only "strange" thing that I'm doing before this is injecting a Market model instance to the request in a middleware).
The problem arises when I go to /products route where is the livewire component included nothing works... The records of the first page are fine, but pagination links are dead and search field does nothing, no console errors, no livewire errors, it's like javascript is not working at all, and here's the strangest thing: if I reload the page, the Market data I loaded in middleware is added to the query string and everything starts working as intended.
Middleware:
public function handle($request, Closure $next) {
$market = Market::findOrFail(session('selected_market'));
$request->request->add(['market' => $market]);
return $next($request);
}
Livewire Component:
class ProductsTable extends Component{
use WithPagination;
public $search = '';
protected $queryString = [
'search' => ['except' => ''],
'page' => ['except' => 1],
];
public function render(){
$products = Product::where('market_id', request('market')->id)
->when($this->search !== '', function($query) {
$query->where('name', 'like', "%{$this->search}%");
$query->orWhere('brand', 'like', "%{$this->search}%");
})->paginate(15);
return view('livewire.products-table', ['products' => $products]);
}
}
Livewire Component View:
<input wire:model.debounce.500ms="search" type="search" name="search" id="search">
<table>
#forelse($products as $product)
<tr onclick="Turbolinks.visit('{{ route('product', $product->id) }}')">
<td>{{ $product->name }}</td>
...
</tr>
#empty
<tr><td>Nothing to show for {{ $search }}</td></tr>
#endforelse
</table>
{{ $products->links() }}
I'm really confused and tired with this, I have no clue what is going on and similar questions haven't been answered clearly.
Thanks
The solution was as simple as adding this to your scripts:
document.addEventListener("turbolinks:load", function(event) {
window.livewire.restart();
});
I created a model relationship between User and Message. I want to implement a list of messages for the authenticated user but I get the following error.
Method Illuminate\Database\Eloquent\Collection::links does not exist
Controller
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('message.index')->with('messages', $user->message);
}
Message provider
class message extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
}
User provider
public function message ()
{
return $this->hasMany('App\Message');
}
index.blade.php
#extends('layouts.app')
#section('content')
<h1>messages</h1>
#if(count($messages)>0)
#foreach ($messages as $message)
<div class="well">
<h3>{{$message->user}}</h3>
<small>Written on {{$message->created_at}} </small>
</div>
#endforeach
{{$messages->links()}}
#else
<p> no post found </p>
#endif
#endsection
Error
"Method Illuminate\Database\Eloquent\Collection::links does not exist.(View: C:\xampp\htdocs\basicwebsite\resources\views\message\index.blade.php)"
Check your view blade, that method (links()) only could be used when your data model is implementing paginate() method.
If you dont use paginate(), remove this part:
{{$messages->links() }}
If you are trying to paginate your data when it gets to the view then you need to add the paginate in your controller before passing the data to the view. Example
return $users = Users::select('id','name')->paginate(10);
with that paginate method in your controller, you can call the links method to paginate your object in view as shown below
{{$users->links()}}
hope it helps you
There are 2 ways to resolve this issue:
Either use paginate function while searching data from database:
$users = DB::table('users')->where('id',$user_id)->paginate(1);
Remove links() function from index.blade.php
{{ $messages->links() }}
Remove {{ $messages->links() }} to in your index.blade.php because {{ $messages->links() }} is supported only when you use paginate
You can do something like this in your controller file.
public function index()
{
$messages = Message::all()->paginate(5);
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('message.index')->with('messages', $messages, $user->message);
}
I am trying to get posts from all users, plus tasks from only the current user. All passed into a single page with a single function and route. It returns an error page instead.
Controller
public function getDashboard()
{
$user = Auth::user();
$userId = $user->id;
$posts = Post::orderBy('created_at', 'desc')->get();
$tasks = Task::where('employee_id', $userId )->get();
return view('dashboard', compact('posts', 'tasks'));
}
Route
Route::get('/dashboard', [
'uses' => 'PostController#getDashboard',
'as' => 'dashboard',
])->middleware('auth');
Blade/View
<div>
#foreach($tasks as $task)
<p data-taskId="{{ $task->id }}">{{ $task->task_body }}</p>
#endforeach
</div>
Looks like possibly a syntax issue, as compact should work fine. Try this in your controller:
return view('dashboard', compact('posts', 'tasks'));
Then in your view, make sure to use the variables and not the class name, and as Karl Hill said, it's used within (), not {{}}:
#foreach($posts as $post)
{{$post->nameOrWhatever}}
#endforeach
#foreach($tasks as $task)
{{$task->nameOrWhatever}}
#endforeach
I want to make a PHP method using laravel. I want to do the comparison of criteria and criteria. Here is the controller code :
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
return view('kriteria_kriterias.create')->with('kriteria1', $kriteria1)->with('kriteria2', $kriteria2)->with('data', $data);
}
and this is the blade code :
It will make the form appear as total of criteria#
The problem is, I can't save it all to database. How do I get it to do this?
Updated method in the controller to the following:
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
How to output in the blade file:
{{ $kriteria1 }}
{{ $kriteria2 }}
Or you update the controller to pass the complete results:
public function create($id1, $id2)
{
$kriteria1 = Model\Kriteria::find($id1);
$kriteria2 = Model\Kriteria::find($id2);
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
And the in the blade you can accss the data in various ways, one way is a foreach loop using blade in the blade template:
#foreach($kriteria1 as $k1)
{{ $k1 }}
#endforeach
#foreach($kriteria2 as $k2)
{{ $k2 }}
#endforeach'
To accept multiple values dynamicaly in the controller you can try something like this:
public function create($ids)
{
$results = collect([]);
foreach($ids as $id) {
$kriteria = Model\Kriteria::findOrFail($id);
if($kriteria) {
$results->put('kriteria' . $id, $kriteria);
}
}
return view('kriteria_kriterias.create')->with($results);
}
Then use the same looping method mentioned above to display them in the blade or a for loop that gets the count and displays accordingly.
maybe you forgot to add the opening tag ;)
{!! Form::open(array('url' => 'foo/bar')) !!}
//put your code in here (line 1-34)
{!! Form::close() !!}