I'm new to laravel.
In RouteServiceProvider when I'm fetching the article using following code
$router->bind('articles',function($id) {
return \App\Article::active()->findOrFail($id);
});
I get an object:
Article {#323 ▼
#fillable: array:18 [▶]
#dates: array:1 [▶]
...
}
But when I build a custom query using QueryBuilder
public static function getArticleById($id) {
return DB::table('articles')
->leftJoin('news','articles.news_id','=','news.id')
->select('articles.*','reports.name as selected_report_id')
->where('articles.id',$id)
->get();
}
I get array:
array:1 [▼
0 => {#342 ▼
+"id": 40
...
}
]
Related
I need to add pagination, but it seems complicated in my case, because I get data from database with paginate, but then I modify this data and when I call links() method on the blade, I get the following exception
Method Illuminate\Support\Collection::links does not exist.
My code in the Controller method:
$transactionsByLastMonth = Transaction::where('created_at', '>=', Carbon::now()->subDays(30)->toDateTimeString())
->where('user_id', Auth::user()->id)
->with(['user', 'propertyFrom', 'propertyTo', 'paddockFrom', 'paddockTo', 'cattleTypeFrom', 'cattleTypeTo'])
->paginate(10);
$transactionsByDays = collect(TransactionResource::collection($transactionsByLastMonth))
->sortByDesc('created_at')
->groupBy(function($date) {
return Carbon::parse($date['created_at'])->format('d');
});
return view('user.reports.index', compact('transactionsByDays'));
Yes, a pagination limits my data to 10 rows, but due to I'm grouping data by days, my collection modifies itself and I can't use $transactionsByDays->links() method to show pagination.
If see dd($transactionsByDays) , it looks like:
Illuminate\Support\Collection {#1381 ▼
#items: array:3 [▼
"01" => Illuminate\Support\Collection {#1019 ▼
#items: array:7 [▼
0 => array:16 [▶]
1 => array:16 [▶]
2 => array:16 [▶]
3 => array:16 [▶]
4 => array:16 [▶]
5 => array:16 [▶]
6 => array:16 [▶]
]
}
31 => Illuminate\Support\Collection {#1386 ▼
#items: array:2 [▼
0 => array:16 [▶]
1 => array:16 [▶]
]
}
30 => Illuminate\Support\Collection {#1384 ▼
#items: array:1 [▼
0 => array:16 [▶]
]
}
]
}
Therefore I need to paginate all arrays together which inside "01", 31, 30...
How can I do it?
Maybe rewrite code above in the controller somehow?
The main aim is that I need to group data to every day according to my json-resource class.
Any ideas?
I've found a solution gyus. I had to pass also a variable transactionsByLastMonth and use links() method over this.
In the meantime I use foreach on the my blade file over transactionsByDays variable. It's correctly works together cause it uses the same data from database, just in the first case its not filtered and not grouped and in the second one it is.
return view('user.reports.index', compact('transactionsByLastMonth', 'transactionsByDays'));
In our web application each user can create multiple nested category by selecting the parent which that specified with category_id column.
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('category_id')->index()->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->string('category_name');
...
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
});
now you supposed one of our user created this category structure:
multiple nested categories children are unlimited, that means every category can be have child and we can't use any static or fixed number for example in for statement to sync the category to specify users.
my question is how can i set specify users to all of categories from parent?
this query only can set users for single child of parent. you can suppose 1,3,4,5,6,7 in above screen shot and not working for 2 and all of their children
children of parent category can be unlimited and how can we set users from the parent to all of nested and children categories?
$category = Category::whereId($request->category_id)->whereNull('category_id')->with('childrenCategories')->first();
$category->users()->sync($request->users);
foreach ($category->childrenCategories as $category) {
$category->users()->sync($request->users);
}
simplified output of query:
App\Entities\Category {#2114 ▼
...
#attributes: array:11 [▶]
#original: array:11 [▶]
...
#relations: array:1 [▼
"childrenCategories" => Illuminate\Database\Eloquent\Collection {#2118 ▼
#items: array:4 [▼
0 => App\Entities\Category {#2133 ▶}
1 => App\Entities\Category {#2134 ▶}
2 => App\Entities\Category {#2135 ▼
...
#attributes: array:11 [▶]
#original: array:11 [▶]
...
#relations: array:1 [▼
"categories" => Illuminate\Database\Eloquent\Collection {#2138 ▼
#items: array:1 [▼
0 => App\Entities\Category {#2157 ▼
...
#attributes: array:11 [▶]
#original: array:11 [▶]
...
#relations: []
...
}
]
}
]
...
}
3 => App\Entities\Category {#2136 ▶}
]
}
]
...
}
You have to use a recursive function like below:
private function syncCategories($category,$request){
if($category->childrenCategories->first()){
foreach ($category->childrenCategories as $childCategory) {
$childCategory->users()->sync($request->users);
$this->syncCategories($childCategory);
}
}
}
I have data I return them into collection but it does not return as i wish and i need help to fix it.
output
array:11 [▼
0 => Collection {#2762 ▼
#items: array:3 [▼
0 => Product {#2758 ▶}
1 => Product {#2759 ▶}
2 => Product {#2760 ▶}
]
}
1 => Collection {#2792 ▼
#items: []
}
2 => Collection {#2948 ▼
#items: []
}
3 => Collection {#3102 ▼
#items: []
}
4 => Collection {#3216 ▼
#items: []
}
5 => Collection {#2886 ▼
#items: array:10 [▶]
}
6 => Collection {#2920 ▼
#items: array:3 [▶]
}
7 => Collection {#3046 ▼
#items: array:12 [▶]
}
8 => Collection {#3074 ▼
#items: []
}
9 => Collection {#3188 ▼
#items: array:7 [▶]
}
10 => Collection {#3288 ▼
#items: []
}
]
Code
$category = Category::where('slug','=',$catslug)->with('childs', 'parent')->first();
$pp1[] = Product::where('category_id',$category->id)->get();
foreach($category->childs as $first){
$pp2[] = Product::where('category_id',$first->id)->get();
if(count($first->childs)> 0){
foreach($first->childs as $second){
$pp3[] = Product::where('category_id',$second->id)->get();
}
}
}
$products = array_merge($pp1,$pp2,$pp3);
dd($products);
What it should return
It should return all products from all arrays in 1 array only and not categorized by Collection {#2792 ▼ I need to get only collections with items and not the ones that are empty.
Any idea?
update
I've also tried this:
$pp1 = [];
$pp2 = [];
$pp3 = [];
$pp1 = Product::where('category_id',$category->id)->get();
foreach($category->childs as $first){
$pp2 = Product::where('category_id',$first->id)->get();
if(count($first->childs)> 0){
foreach($first->childs as $second){
$pp3 = Product::where('category_id',$second->id)->get();
}
}
}
it returns:
array_merge(): Argument #1 is not an array
You can get all products of the category, of its children and of its grand-children as,
$category = Category::where('slug','=',$catslug)
->with([
'products',
'childs.products',
'childs.childs.products',
'parent'
])
->first()
->toArray();
$products = array_merge([
data_get($category, 'products'),
array_collapse(data_get($category, 'childs.*.products')),
array_collapse(data_get($category, 'childs.*.childs.*.products'))
]);
Fiddle : https://implode.io/ebXrD8
I want to save a request from my laravel 5.2 app a form into my database:
When I submit the request with the word testdy I get an exception:
FatalThrowableError in KeywordController.php line 49: Class
'App\Keyword' not found
Line 49 in my controller is when I want to built my model: $keyword = new Keyword($request);
Below you can find the code of the KeywordController:
<?php
namespace App\Http\Controllers;
use App\Keyword;
use App\Http\Requests\KeywordRequest;
use Response;
use Sentinel;
class KeywordController extends JoshController
{
public function __construct()
{
parent::__construct();
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
// Grab all the Keywords
// $Keywords = Keyword::all();
// Show the page
return View('admin.keyword.index'); //, compact('Keywords'));
}
public function create()
{
// $Keywordcategory = KeywordCategory::lists('title', 'id');
return view('admin.keyword.create'); //, compact('Keywordcategory'));
}
public function store(KeywordRequest $request)
{
//dd($request);
$keyword = new Keyword($request); //line 49 of my controller
$keyword->user_id = Sentinel::getUser()->id;
$keyword->save();
if ($keyword->id) {
return redirect('admin/keyword')->with('success', trans('Keyword/message.success.create'));
} else {
return Redirect::route('admin/keyword')->withInput()->with('error', trans('Keyword/message.error.create'));
}
}
public function show(Keyword $keyword)
{
$comments = Keyword::all();
return view('admin.keyword.show', compact('Keyword', 'comments', 'tags'));
}
public function edit(Keyword $keyword)
{
$Keywordcategory = KeywordCategory::lists('title', 'id');
return view('admin.keyword.edit', compact('Keyword', 'Keywordcategory'));
}
public function update(KeywordRequest $request, Keyword $Keyword)
{
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/Keyword/';
$picture = str_random(10).'.'.$extension;
$Keyword->image = $picture;
}
if ($request->hasFile('image')) {
$destinationPath = public_path().$folderName;
$request->file('image')->move($destinationPath, $picture);
}
$Keyword->retag($request['tags']);
if ($Keyword->update($request->except('image', '_method', 'tags'))) {
return redirect('admin/keyword')->with('success', trans('Keyword/message.success.update'));
} else {
return Redirect::route('admin/keyword')->withInput()->with('error', trans('Keyword/message.error.update'));
}
}
public function getModalDelete(Keyword $Keyword)
{
$model = 'Keyword';
$confirm_route = $error = null;
try {
$confirm_route = route('delete/Keyword', ['id' => $Keyword->id]);
return View('admin/layouts/modal_confirmation', compact('error', 'model', 'confirm_route'));
} catch (GroupNotFoundException $e) {
$error = trans('Keyword/message.error.delete', compact('id'));
return View('admin/layouts/modal_confirmation', compact('error', 'model', 'confirm_route'));
}
}
public function destroy(Keyword $Keyword)
{
if ($Keyword->delete()) {
return redirect('admin/keyword')->with('success', trans('Keyword/message.success.delete'));
} else {
return Redirect::route('admin/keyword')->withInput()->with('error', trans('Keyword/message.error.delete'));
}
}
}
My request, see the dd($request); looks like the following:
KeywordRequest {#323 ▼
#container: Application {#3 ▶}
#redirector: Redirector {#330 ▼
#generator: UrlGenerator {#114 ▼
#routes: RouteCollection {#26 ▶}
#request: Request {#40 ▶}
#forcedRoot: null
#forceSchema: null
#cachedRoot: null
#cachedSchema: null
#rootNamespace: "App\Http\Controllers"
#sessionResolver: Closure {#115 ▶}
#dontEncode: array:14 [▶]
}
#session: Store {#264 ▼
#id: "6db1ef2a6ede612fa681e299c7731866afce7b34"
#name: "laravel_session"
#attributes: array:4 [▼
"_token" => "HbguKauEYhU00n9YcCvw8lloKWbd51I6FOhHRORB"
"_previous" => array:1 [▶]
"flash" => array:2 [▶]
"cartalyst_sentinel" => "5jqJ2R6MTFm4DkOefwhknOD3WY4Jaa0T"
]
#bags: []
#metaBag: MetadataBag {#255 ▼
-name: "__metadata"
-storageKey: "_sf2_meta"
#meta: &120 array:3 [▼
"u" => 1492269234
"c" => 1492243279
"l" => "0"
]
-lastUsed: 1492269215
-updateThreshold: 0
}
#bagData: array:1 [▶]
#handler: FileSessionHandler {#265 ▼
#files: Filesystem {#117}
#path: "/home/ubuntu/workspace/storage/framework/sessions"
#minutes: 120
}
#started: true
}
}
#redirect: null
#redirectRoute: null
#redirectAction: null
#errorBag: "default"
#dontFlash: array:2 [▼
0 => "password"
1 => "password_confirmation"
]
#json: null
#convertedFiles: []
#userResolver: Closure {#232 ▼
class: "Cartalyst\Sentinel\Laravel\SentinelServiceProvider"
this: SentinelServiceProvider {#77 …}
use: {▼
$app: Application {#3}
}
file: "/home/ubuntu/workspace/vendor/cartalyst/sentinel/src/Laravel/SentinelServiceProvider.php"
line: "425 to 427"
}
#routeResolver: Closure {#233 ▼
class: "Illuminate\Routing\Router"
this: Router {#24 …}
use: {▼
$route: Route {#149 ▼
#uri: "admin/keyword/create"
#methods: array:1 [▶]
#action: array:6 [▶]
#defaults: []
#wheres: array:1 [▶]
#parameters: []
#parameterNames: []
#compiled: CompiledRoute {#239 ▶}
#router: Router {#24 …}
#container: Application {#3}
}
}
file: "/home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Routing/Router.php"
line: "693 to 695"
}
+attributes: ParameterBag {#325 ▼
#parameters: []
}
+request: ParameterBag {#322 ▼
#parameters: array:2 [▼
"_token" => "HbguKauEYhU00n9YcCvw8lloKWbd51I6FOhHRORB"
"keyword" => "tesdy"
]
}
+query: ParameterBag {#324 ▼
#parameters: []
}
+server: ServerBag {#328 ▼
#parameters: array:42 [▶]
}
+files: FileBag {#327 ▼
#parameters: []
}
+cookies: ParameterBag {#326 ▼
#parameters: array:2 [▼
"XSRF-TOKEN" => "HbguKauEYhU00n9YcCvw8lloKWbd51I6FOhHRORB"
"laravel_session" => "6db1ef2a6ede612fa681e299c7731866afce7b34"
]
}
+headers: HeaderBag {#329 ▼
#headers: array:16 [▼
"host" => array:1 [▶]
"content-length" => array:1 [▶]
"cache-control" => array:1 [▶]
"origin" => array:1 [▶]
"upgrade-insecure-requests" => array:1 [▶]
"user-agent" => array:1 [▶]
"content-type" => array:1 [▶]
"accept" => array:1 [▶]
"referer" => array:1 [▶]
"accept-encoding" => array:1 [▶]
"accept-language" => array:1 [▶]
"cookie" => array:1 [▶]
"x-forwarded-proto" => array:1 [▶]
"x-forwarded-port" => array:1 [▶]
"x-forwarded-for" => array:1 [▶]
"connection" => array:1 [▶]
]
#cacheControl: array:1 [▼
"max-age" => "0"
]
}
#content: ""
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: null
#requestUri: null
#baseUrl: null
#basePath: null
#method: "POST"
#format: null
#session: Store {#264 ▶}
#locale: null
#defaultLocale: "en"
}
The "keyword" => "tesdy" parameter has the same name in the database.
Any suggestions why $keyword = new Keyword($request); throws an exception?
I appreciate your replies!
Update
My app/Keyword.php file looks like the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Keywords extends Model
{
protected $table = 'keywords';
protected $guarded = ['id'];
}
Model name should be Keyword, change it and this will solve the problem:
class Keyword extends Model
Just change the class name to Keyword from Keywords in your app/Keyword.php. The class name should equals to its file name.
I have some nested query in my application such as example follow.
$arrData = DB::table('service as tsv')
->select($afields)
->join('shops as ts', 'ts.id', '=', 'tsv.shop_id')
->where('ts.name','like','%'.$searchstring.'%');
if(!empty($type) && $type == 'individual')
$arrData->where('ts.type','=', '1');
$arrData->groupBy('tsv.id')->get();
This query not returning the exact output it display the content like
Builder {#351 ▼
#connection: MySqlConnection {#336 ▶}
#grammar: MySqlGrammar {#347 ▶}
#processor: MySqlProcessor {#348}
#bindings: array:5 [▶]
+aggregate: null
+columns: array:7 [▶]
+distinct: false
+from: "service as tsv"
+joins: array:3 [▶]
+wheres: array:3 [▶]
+groups: array:1 [▶]
+havings: null
+orders: array:1 [▶]
+limit: 4
+offset: 0
+unions: null
+unionLimit: null
+unionOffset: null
+unionOrders: null
+lock: null
#backups: []
#operators: array:26 [▶]
#useWritePdo: false
}
I want to display the data how should I access the data from this situation.